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

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.
主站蜘蛛池模板: 阳曲县| 泊头市| 松江区| 台南市| 穆棱市| 临泽县| 乐安县| 衡南县| 玉林市| 五指山市| 富平县| 左权县| 岳普湖县| 环江| 赤壁市| 南昌县| 沈阳市| 铁岭市| 夹江县| 永顺县| 浠水县| 辛集市| 南平市| 巴林右旗| 宁南县| 上栗县| 普安县| 郎溪县| 英吉沙县| 南汇区| 乌鲁木齐县| 浠水县| 南康市| 淄博市| 鹤壁市| 寿光市| 鹤壁市| 新化县| 萍乡市| 保德县| 马关县|