我已经阅读了有关此主题的各种网站,但我还没有弄清楚为什么我们需要 runInAction
方法以及它到底是如何工作的。
有人可以向我解释一下 runInAction
功能吗?
谢谢。
最佳答案
简短的回答是:您实际上并不需要 runInAction
。您可以编写一个应用程序而不使用它,并且它应该可以正常工作。
但是,如果您正在开发更大的代码库,并且想要实现一些最佳实践,则可以使用 mobx 功能 "enforce actions / strict mode" ,它基本上强制对状态的任何修改都必须在操作内部发生。这很有用,因为操作使状态变化的原因变得显而易见,并且它们在 mobx 开发工具中提供了有用的调试信息。
通过使用此配置标志,如果您尝试修改操作之外的状态,mobx 将抛出错误。
<小时/>好吧,runInAction
是什么?
这是一个没有 runInAction
的示例:
loadWeather = city => {
fetch(
`https://abnormal-weather-api.herokuapp.com/cities/search?city=${city}`
)
.then(response => response.json())
.then(data => {
this.setWeatherData(data); // <==== here
});
};
@action
setWeatherData = data => {
this.weatherData = data;
};
由于我们使用严格模式,因此我们必须定义一个新操作来设置天气数据。
当必须定义一个操作只是为了使用一次时,这很快就会变得乏味。
这里出现了runInAction
,使其变得更短:
loadWeatherRunInThen = city => {
fetch(`https://abnormal-weather-api.herokuapp.com/cities/search?city=${city}`)
.then(response => response.json())
.then(data => {
runInAction(() => {
this.weatherData = data; // <====== We dont have to define an action
});
});
};
所以基本上,runInAction
获取一段代码并在匿名操作中执行它,而不必为其手动创建操作。
有关更多信息,请查看以下链接:
- https://github.com/mobxjs/mobx/blob/mobx4and5/docs/refguide/action.md#runinactionname-thunk
- https://github.com/mobxjs/mobx/blob/mobx4and5/docs/refguide/api.md#configure
- https://www.leighhalliday.com/mobx-async-actions
编辑:
上面的答案是在 Mobx 4 时代左右的。
对于 Mobx 6:
By default, MobX 6 and later require that you use actions to make changes to the state. However, you can configure MobX to disable this behavior.
新文档的链接:
https://mobx.js.org/actions.html#runinaction
https://mobx.js.org/actions.html#disabling-mandatory-actions-
关于javascript - Mobx - runInAction() 用法。为什么我们需要它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57271153/