繁体   English   中英

异步等待`this`没有用babel定义

[英]Async await `this` is not defined with babel

我在使用异步等待中有一个问题,这是我的.babelrc

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

我没有问题,使用异步伺机调用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>
  }
}

this是对执行中的当前对象的引用,在内部保证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}) ;
  }

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

这工作

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM