javascriptreactjsmobx

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


Why do we need the runInAction method and how exactly does it work?

Can someone explain to me runInAction functionality?


Solution

  • The short answer is: you don't really need runInAction. You can write an application without using it, and it should work just fine.

    But if you're working on a larger codebase, and you want to enforce some best practices, you can use the mobx feature "enforce actions / strict mode", which basically enforces that any modification to the state must happen inside of an action. This is useful because actions make it obvious why a piece of state changed, and they provide useful debugging information in the mobx devtools.

    By using this configuration flag, mobx will throw an error if you try to modify the state outside of an action.


    Alright, what is runInAction ?

    Here's an example without 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;   
    };
    

    Since we are using strict mode, we had to define a new action just to set the weatherData.

    This can get tedious pretty quickly, when having to define an action just to use it once.

    Here comes runInAction to make it much shorter:

    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
          });
        });
    };
    

    So basically, runInAction takes a piece of code and executes it in an anonymous action, instead of having to manually create an action for it.

    For more information, check these links:


    Edit:

    The answer above was around the days of Mobx 4.

    For 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.

    Links to the new documentation:

    https://mobx.js.org/actions.html#runinaction

    https://mobx.js.org/actions.html#disabling-mandatory-actions-

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