Using the MobX @action decorator with async functions and .then

后端 未结 3 698
一整个雨季
一整个雨季 2021-02-19 05:02

I\'m using MobX 2.2.2 to try to mutate state inside an async action. I have MobX\'s useStrict set to true.

@action someAsyncFunction(args) {
  fetch(`http://loca         


        
3条回答
  •  迷失自我
    2021-02-19 05:29

    Do I need to supply the @action decorator to the second .then statement? Any help would be appreciated.

    This is pretty close to the actual solution.

    .then(json => this.someStateProperty = json)
    

    should be

    .then(action(json => this.someStateProperty = json))
    

    Keep in mind action can be called in many ways that aren't exclusive to @action. From the docs on action:

    • action(fn)
    • action(name, fn)
    • @action classMethod
    • @action(name) classMethod
    • @action boundClassMethod = (args) => { body }
    • @action(name) boundClassMethod = (args) => { body }

    are all valid ways to mark a function as an action.

    Here's a bin demonstrating the solution: http://jsbin.com/peyayiwowu/1/edit?js,output

    mobx.useStrict(true);
    const x = mobx.observable(1);
    
    // Do async stuff
    function asyncStuff() {
      fetch('http://jsonplaceholder.typicode.com/posts')
        .then((response) => response.json())
        // .then((objects) => x.set(objects[0])) BREAKS
        .then(mobx.action((objects) => x.set(objects[0])))
    }
    
    asyncStuff()
    

    As for why your error actually happens I'm guessing that the top level @action doesn't recursively decorate any functions as actions inside the function it's decorating, meaning your anonymous function passed into your promise wasn't really an action.

提交回复
热议问题