Be aware of short-circuited code in reactions and computeds

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:

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 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.:

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
  }
});

results matching ""

    No results matching ""