【问题标题】:Async await `this` is not defined with babel异步等待`this`没有用 babel 定义
【发布时间】:2018-03-14 10:16:37
【问题描述】:

我在 react 中使用异步等待时遇到问题,这是我的 .babelrc

{
  "presets": [
    ["es2015", {"modules": false}],
    "stage-2",
    "react"
  ],
  "plugins": [
    "react-hot-loader/babel",
    "transform-async-to-generator",
    ["transform-runtime", {
      "polyfill": false,
      "regenerator": true
    }]
  ]
}

我使用 async await 调用 api 没有问题,但无法 setState,因为 this 未定义

class App extends Component {

  testAsync = async () => {
    const { body } = await requestOuter('GET', 'https://api.github.com/users')
    console.log(body) //working, body is bunch of array of object
    this.setState({body}) //this is not defined error?
  }

  render() {
    return <div>
    <button onClick={() => this.testAsync()}>test async</button>
      {(this.state.body || []).map(o => o.login)}
    </div>
  }
}

【问题讨论】:

  • 你使用的是什么版本的transform-async-to-generatorgithub.com/babel/babel/issues/2765
  • 您像 var 一样定义 testAsync,.. 您希望它成为该类的方法,只需执行 .. async testAsync() { 事实上,对于 Babel,您所做的事情我得到了一个错误.
  • 你能在这个 sn-p 的 babel 编译后发布输出吗?
  • @Keith 那有什么问题?假设一个函数可以分配给一个 var?
  • @SharonChai what's wrong with that? 你定义了一个类,Component { 这之后的代码不是任何函数的主体,甚至不是构造函数。所以这基本上是一个语法错误。为什么不尝试我的建议?.. 简单地说,async testAsync() {,这就是您将方法绑定到类的方式,无需分配。

标签: javascript reactjs ecmascript-6 babeljs


【解决方案1】:

this 是对当前执行对象的引用,promise 内部this 与应用范围不同。

尝试:

<button onClick={() => {var self=this; this.testAsync(self);}}>test async</button>

.

testAsync = async (self) => {
    const { body } = await requestOuter('GET', 'https://api.github.com/users')
    console.log(body) //working, body is bunch of array of object
    self.setState({body}) ;
  }

您必须尝试这种方法的变体。一种变体应根据应用范围起作用。

【讨论】:

    【解决方案2】:

    成功了

    async testAsync() {
        const { body } = await requestOuter('GET', 'https://api.github.com/users')
        console.log(body) //working, body is bunch of array of object
        this.setState({body}) //this is not defined error?
      }
    

    我必须在 jsx 中使用箭头函数

    更新:这是由 react-hot-loader 引起的,哇没想到! https://github.com/gaearon/react-hot-loader/issues/391

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-31
      • 2019-12-18
      • 1970-01-01
      • 1970-01-01
      • 2018-04-27
      • 2021-04-15
      • 2015-09-28
      • 1970-01-01
      相关资源
      最近更新 更多