使用带有异步函数和

使用带有异步函数和

本文介绍了使用带有异步函数和.then的MobX @action装饰器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用MobX 2.2.2尝试在异步操作中改变状态。我将MobX的useStrict设置为true。

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://localhost:8080/some_url`, {
    method: 'POST',
    body: {
      args
    }
  })
  .then(res => res.json())
  .then(json => this.someStateProperty = json)
  .catch(error => {
    throw new Error(error)
  });
}

我得到:

Error: Error: [mobx] Invariant failed: It is not allowed to create or change state outside an `action` when MobX is in strict mode. Wrap the current method in `action` if this state change is intended

我是否需要提供@动作装饰到第二个.then声明?任何帮助将不胜感激。

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)

应该是

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

请记住 action 可以通过多种方式调用不属于 @action 。来自:

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}

  • 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()

至于为什么你的错误实际发生我猜测顶层 @action 不会递归地装饰任何函数作为里面的动作它正在装饰的功能,意味着您的匿名函数传递到您的承诺中并非真正的操作

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.

这篇关于使用带有异步函数和.then的MobX @action装饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 11:35