- MobX Quick Start Guide
- Pavan Podila Michel Weststrate
- 254字
- 2021-08-05 10:34:24
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.
推薦閱讀
- 物聯(lián)網(wǎng)工程規(guī)劃技術(shù)
- 萬物互聯(lián):蜂窩物聯(lián)網(wǎng)組網(wǎng)技術(shù)詳解
- 計算機網(wǎng)絡(luò)安全實訓(xùn)教程(第二版)
- PLC、現(xiàn)場總線及工業(yè)網(wǎng)絡(luò)實用技術(shù)速成
- Wireshark網(wǎng)絡(luò)分析就這么簡單
- Socket.IO Real-time Web Application Development
- 物聯(lián)網(wǎng)技術(shù)與應(yīng)用
- 光纖通信系統(tǒng)與網(wǎng)絡(luò)(修訂版)
- 網(wǎng)絡(luò)綜合布線(第2版)
- 大型企業(yè)微服務(wù)架構(gòu)實踐與運營
- 黑客心理學(xué):社會工程學(xué)原理
- 互聯(lián)網(wǎng)視覺設(shè)計(全彩慕課版)
- 5G智聯(lián)萬物:輕松讀懂5G應(yīng)用與智能未來
- 世界網(wǎng)力:2018年中國網(wǎng)信產(chǎn)業(yè)桔皮書
- 夢工廠之沸騰關(guān)鍵幀:Maya動畫手冊