Mobx - runInAction() 用法。我们为什么需要它?

Mobx - runInAction() usage. Why do we need it?

我已经阅读了有关此主题的各种网站,但我还没有弄清楚为什么我们需要 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 获取一段代码并在匿名操作中执行它,而不必手动为其创建操作。

有关详细信息,请查看以下链接:


编辑:

上面的答案是在 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-

https://mobx.js.org/configuration.html#enforceactions