There are lots of factors determining the optimum O/F. Isp can usually be increased by running a bit richer (lower O/F) than stoichiometric, in part because the molecular weight of the fuel is usually lower than that of the oxidizer (over simplifying a bit), resulting in a higher sound speed for the exhaust products. There is a lengthy discussion
here.
To increase Isp for a given nozzle expansion, one also wants a low ratio of specific heats in the exhaust, in other words, more simpler molecules that have fewer ways to retain energy. That's a reason you might want more H
2 and less H
2O in the exhaust of an O
2-H
2 engine.
Though we often forget this, maximization of Isp is not in and of itself desirable, in that it's often better to run at an O/F that gives a slightly higher overall density, so that tankage of a given size will hold a little more impulse. The
trade between Isp and density depends on the required delta-V and the relationship between propellant volume and vehicle mass.
In fact, the ideal O/F changes with time. Just to illustrate the concept, suppose you had a rocket of fixed overall volume sitting on the launching pad that could easily operate and any mixture ratio. Now consider the first drop of propellants burned. That mass of that drop will not need to be accelerated, so it might as well pack the most impulse possible, i.e., it should be optimized for maximum impulse density (impulse per unit volume). Subsequent drops of propellant should be weighted more and more toward Isp, as their masses matter.
Optimum O/F might be affected by other things too. Consider the Saturn V's third stage, which achieved orbital insertion and was then restarted a few hours later for trans-lunar injection. While the stage was coasting in LEO, hydrogen was boiling off. There was very little boil-off of oxygen, however, because boiled-off hydrogen was used to cool the lox. The fact that lox was relatively stable while hydrogen was a wasting asset affects the optimal O/F for the TLI burn, under the constraint of a fixed size or mass of the stage.
In the example of lox-hydrogen propellant cycle, where the propellants come from ISRU, the overabundance of oxygen might lead one to run engines at a higher O/F to maximize the efficiency of the entire system (including the propellant production part), at the modest expense of vehicle mass efficiency. You always need to keep in mind what it is you're maximizing (hint: it's never Isp).