Be aware of short-circuited code in reactions
MobX reactions (i.e. observers, autoRuns, reactions) and computeds are re-evaluated whenever any observables they access are changed. The caveat is that the reaction in question must have previously accessed the observable for it to be re-evaluated. Short-circuit if
expressions can often create a situation where, in the initial evaluation, the observable you intended to be observed was not accessed and so future changes to it do not result in the re-evaluation of the reaction.
For example:
import { autorun, observable} from 'mobx';
class MyClass {
@observable isOnline = false;
@observable hasError = false;
}
const obj = new MyClass();
autorun(() => {
if (!obj.isOnline || obj.hasError) {
// do something
}
});
The first time the above autorun
executes, it will not access the hasError
observable. So, if later, hasError
is set to true
without isOnline
first getting set to true
, the autorun
will not re-evaluate. (Once isOnline
becomes true
, only then this autorun
will actually observe hasError
.)
To prevent this from happening, access all observables that can change independently outside of short-circuited expressions, i.e.:
import { autorun, observable} from 'mobx';
class MyClass {
@observable isOnline = false;
@observable hasError = false;
}
const obj = new MyClass();
autorun(() => {
const isOnline = obj.isOnline;
const hasError = obj.hasError;
if (!isOnline || hasError) {
// do something
}
});
Last updated
Was this helpful?