简体   繁体   中英

Async await `this` is not defined with babel

I have a problem using async await in react, this is my .babelrc

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

I don't have problem using async await to call api but can't setState because the this is not defined

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 is reference to current object in execution, inside promise this is not same as application scope.

try:

<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}) ;
  }

You have to try variation of this of this approach. One variation should work as per scope of application.

This worked

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?
  }

and I have to use arrow function in the jsx

Update: this is caused by react-hot-loader, wow didn't expect that! https://github.com/gaearon/react-hot-loader/issues/391

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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