- 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.
推薦閱讀
- 重新定義Spring Cloud實(shí)戰(zhàn)
- 萬物互聯(lián):蜂窩物聯(lián)網(wǎng)組網(wǎng)技術(shù)詳解
- HTML5 Game development with ImpactJS
- Getting Started with Grunt:The JavaScript Task Runner
- 物聯(lián)網(wǎng)長距離無線通信技術(shù)應(yīng)用與開發(fā)
- Working with Legacy Systems
- Getting Started with nopCommerce
- 云工廠:開啟中國制造云時代
- Python API Development Fundamentals
- Hands-On Reactive Programming in Spring 5
- Python Web Scraping Cookbook
- 黑客與反黑工具使用詳解
- Microservices Development Cookbook
- 視聽變革:廣電的新媒體戰(zhàn)略
- 巧學(xué)活用CISCO網(wǎng)絡(luò)典型配置