使用带有异步函数和.then的MobX @action装饰器

时间:2016-05-31 20:12:30

标签: javascript mobx

我正在使用MobX 2.2.2尝试在异步操作中改变状态。我将MobX的useStrict设置为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

我是否需要将@action装饰器提供给第二个.then语句?任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:18)

  

我是否需要将@action装饰器提供给第二个.then语句?任何帮助将不胜感激。

这与实际解决方案非常接近。

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

应该是

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

请注意action可以通过多种方式调用@action。来自the docs on action

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

是将函数标记为操作的所有有效方法。

这是一个展示解决方案的垃圾箱: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没有递归地装饰任何函数作为它正在装饰的函数内的动作,这意味着你的匿名函数传递到你的诺言并不是真的action

答案 1 :(得分:8)

补充上述答案;实际上,action仅适用于您传递给它的函数。 then中的函数在一个单独的堆栈上运行,因此应该可以识别为单独的操作。

请注意,您还可以为操作指定名称,以便在使用这些操作时轻松识别它们:

then(action("update objects after fetch", json => this.someStateProperty = json))

答案 2 :(得分:2)

请注意,在async方法中,您必须在等待某事后开始新的操作/事务:

@mobx.action async someAsyncFunction(args) {
  this.loading = true;

  var result = await fetch(`http://localhost:8080/some_url`, {
    method: 'POST',
    body: {
      args
    }
  });
  var json = await result.json();
  @mobx.runInAction(()=> {
     this.someStateProperty = json
     this.loading = false;
  });
}

我的偏好

我更喜欢不直接使用@ mobx.action / runInAction,但始终将其放在private方法上。让public方法调用实际更新状态的私有方法:

public someAsyncFunction(args) {
  this.startLoading();
  return fetch(`http://localhost:8080/some_url`, {
    method: 'POST',
    body: {
      args
    }
  })
  .then(res => res.json())
  .then(this.onFetchResult);
}

@mobx.action 
private startLoading = () => {
   this.loading = true;
}

@mobx.action 
private onFetchResult = (json) => {
   this.someStateProperty = json;
   this.loading = false;
}
相关问题