enforceWritePolicy method
void
enforceWritePolicy(
- Atom atom
)
Implementation
void enforceWritePolicy(Atom atom) {
// Cannot mutate observables inside a computed. This is required to maintain the consistency of the reactive system.
if (_state.computationDepth > 0 && atom.hasObservers) {
throw MobXException(
'Computed values are not allowed to cause side effects by changing observables that are already being observed. Tried to modify: ${atom.name}');
}
// ---
// We are wrapping in an assert() since we don't want this code to execute at runtime.
// The dart compiler removes assert() calls from the release build.
// ---
assert(() {
switch (config.writePolicy) {
case ReactiveWritePolicy.never:
break;
case ReactiveWritePolicy.observed:
if (atom.hasObservers == false) {
break;
}
assert(_state.isWithinBatch,
'Side effects like changing state are not allowed at this point. Please wrap the code in an "action". Tried to modify: ${atom.name}');
break;
case ReactiveWritePolicy.always:
assert(_state.isWithinBatch,
'Changing observable values outside actions is not allowed. Please wrap the code in an "action" if this change is intended. Tried to modify ${atom.name}');
}
return true;
}());
}