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 ifexpressions 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:
1
import { autorun, observable} from 'mobx';
2
3
class MyClass {
4
@observable isOnline = false;
5
@observable hasError = false;
6
}
7
8
const obj = new MyClass();
9
10
autorun(() => {
11
if (!obj.isOnline || obj.hasError) {
12
// do something
13
}
14
});
Copied!
The first time the above autorunexecutes, it will not access the hasErrorobservable. So, if later, hasErroris set to truewithout isOnlinefirst getting set to true, the autorunwill not re-evaluate. (Once isOnlinebecomes true, only then this autorunwill actually observe hasError.)
To prevent this from happening, access all observables that can change independently outside of short-circuited expressions, i.e.:
1
import { autorun, observable} from 'mobx';
2
3
class MyClass {
4
@observable isOnline = false;
5
@observable hasError = false;
6
}
7
8
const obj = new MyClass();
9
10
autorun(() => {
11
const isOnline = obj.isOnline;
12
const hasError = obj.hasError;
13
if (!isOnline || hasError) {
14
// do something
15
}
16
});
Copied!
Last modified 1yr ago
Copy link