【问题标题】:How to include multiple await calls in MobX action如何在 MobX 操作中包含多个等待调用
【发布时间】:2017-11-10 09:07:10
【问题描述】:

我正在开发一个需要在 MobX 操作中使用 await 语法进行多次调用的应用程序。一个典型的例子是这样的:

  @action.bound
  async mintToken() {
    const tokenInstance = await this.token.deployed();    
    await tokenInstance.mint(1, { from: this.account });
    await this.updateLastMintedToken();
    await this.updateTokenDetails();
  }

但是,由于 MobX 处理操作的方式,此代码似乎无法正确执行。根据docs

@action 仅适用于代码块,直到第一次等待。和 每次等待之后都会启动一个新的异步函数,因此在每次等待之后 等待,状态修改代码应该被包装为动作。

文档中给出的示例使用runAsAction,我在以下代码中进行了尝试:

  @action.bound
  async updateLastMintedToken() {
    const tokenInstance = await this.token.deployed();

    runInAction(async function() {
      const result = await tokenInstance.lastTokenMinted.call();
      this.lastTokenMinted = result.toNumber();
    });

  }

不幸的是,这不起作用,因为 thisrunInAction 调用中变得未定义,所以我无法改变状态。

非常感谢在一个操作中运行多个异步调用的任何方向!

【问题讨论】:

  • “很遗憾,这不起作用,因为它在 runInAction 调用中变得未定义,所以我无法改变状态” 您是否尝试过为 runInAction 使用箭头函数?

标签: javascript asynchronous mobx


【解决方案1】:

您可以使用箭头函数将runInAction 中的上下文设置为与updateLastMintedToken 函数相同的上下文

  @action.bound
  async updateLastMintedToken() {
    const tokenInstance = await this.token.deployed();

    runInAction(async () => {
      const result = await tokenInstance.lastTokenMinted.call();
      this.lastTokenMinted = result.toNumber();
    });

  }

【讨论】:

  • function runInAction(fn) { fn() } const o = { abc:123, updateLastMintedToken() { runInAction(async () => {console.log(this)}) } }; o.updateLastMintedToken()
猜你喜欢
  • 2019-12-29
  • 2020-02-20
  • 2019-05-18
  • 2018-04-03
  • 1970-01-01
  • 2016-08-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多