首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Async await `this`未使用babel定义

Async await `this`未使用babel定义
EN

Stack Overflow用户
提问于 2018-03-14 18:16:38
回答 2查看 998关注 0票数 0

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

代码语言:javascript
复制
{
  "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没有问题,但由于this未定义,无法使用setState

代码语言:javascript
复制
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>
  }
}
EN

回答 2

Stack Overflow用户

发布于 2018-03-14 20:53:58

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

尝试:

代码语言:javascript
复制
<button onClick={() => {var self=this; this.testAsync(self);}}>test async</button>

代码语言:javascript
复制
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}) ;
  }

您必须尝试此方法的变体。一种变体应该根据应用范围而工作。

票数 0
EN

Stack Overflow用户

发布于 2018-03-15 10:54:21

这很管用。

代码语言:javascript
复制
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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49275060

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档