官术网_书友最值得收藏!

Enforcing the use of actions

It should come as no surprise that MobX strongly recommends using actions for modifying observables. In fact, this can be made mandatory by configuring MobX to always enforce this policy, also called the strict mode. The configure() function can be used to set the enforceActions option to true. MobX will now throw an error if you try to modify an observable outside of an action.

Going back to our previous example with cart, if we try to modify it outside an action, MobX will fail with an error, as you can see from the following example:

import { observable, configure } from 'mobx';

configure({
enforceActions: true,
});

// Modifying outside of an action
cart.items.push({ name: 'test', quantity: 1 });
cart.modified = new Date();

Error: [mobx] Since strict-mode is enabled, changing observed observable values outside actions is not allowed. Please wrap the code in an `action` if this change is intended. Tried to modify: ObservableObject@1.items
There is one little thing to remember regarding the use of configure({ enforceActions: true }): It will only throw errors if there are observers watching the observables that you are trying to mutate. If there are no observers for those observables, MobX will safely ignore it. This is because there is no risk of triggering reactions too early. However, if you do want to be strict about this, you can also set { enforceActions: 'strict' }. This will throw an error even if there are no observers attached to the mutating observables.
主站蜘蛛池模板: 宁远县| 永年县| 仁怀市| 娱乐| 全南县| 当涂县| 霞浦县| 铜陵市| 垫江县| 龙岩市| 宝鸡市| 会昌县| 江川县| 湖州市| 攀枝花市| 赣州市| 仁布县| 密山市| 丹江口市| 怀化市| 陆川县| 富裕县| 郸城县| 宁明县| 宾川县| 灵寿县| 大庆市| 盘山县| 郑州市| 内乡县| 漳平市| 赞皇县| 兴仁县| 临武县| 哈密市| 松潘县| 丘北县| 小金县| 稷山县| 车险| 湟中县|