简体   繁体   中英

ReactJS: Uncaught TypeError: Cannot read property 'setState' of undefined

I'm currently trying to build a small weather app in reactJS (the one for freecodecamp)

currently I'm getting the error: "Uncaught TypeError: Cannot read property 'setState' of undefined"

here is a link to the codepen: http://codepen.io/rasmus/pen/aNGRJm

and here is the code that's the problem I guess:

  componentDidMount: () => {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition((position) => {
        $.ajax({
          url: URL + "lat=" + position.coords.latitude + "&lon=" + position.coords.longitude + "&APPID=" + APIKEY,
          success: (data) => {
            this.setState({data: data})
          }
        });
      })   
    }
  },

the url is not the problem. I can log the data I'm receiving to the console.

I guess it's because of the scope of this ..

any ideas?

EDIT: I don't think that this is a duplicate because I'm only using arrow functions and they are making .bind(this) obsolete

The callback in your ajax function is called not from within your function, so the this is not pointing to what you expect, ie, your class.

Save a reference and use it from there:

componentDidMount: () => {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition((position) => {
        let self = this;
        $.ajax({
          url: URL + "lat=" + position.coords.latitude + "&lon=" + position.coords.longitude + "&APPID=" + APIKEY,
          success: (data) => {
            self.setState({data: data})
          }
        });
      })   
    }
  },

Try to use arrow function like follows in componentDidMount:

componentDidMount = () => {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition((position) => {
        let self = this;
        $.ajax({
          url: URL + "lat=" + position.coords.latitude + "&lon=" + position.coords.longitude + "&APPID=" + APIKEY,
          success: (data) => {
            self.setState({data: data})
          }
        });
      })   
    }
}

You need to cache the reference to this outside of that API call. The arrow function binds this for you so you can access it within the function and it will still point to the component.

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