未处理的拒绝(TypeError):写入 this.setState(data) 时未定义;在 componentDidMount 函数中

IT技术 javascript reactjs
2021-04-28 03:26:40

当我在没有this.setState(data);一切的情况下使用这个函数时,我在控制台中看到了来自 API 的数据。

当我this.setState(data);在下设置时console.log(data);我收到如下错误:

Unhandled Rejection (TypeError): this is undefined
componentDidMount/<
src/App.js:42

  39 |       let data = await response.json();
  40 |       
  41 |       console.log(data);
> 42 |       this.setState(data);
     | ^  43 |     });
  44 |   }
  45 | }

代码:

     componentDidMount() {
    if (navigator.geolocation) {
      navigator.geolocation.watchPosition(async function (position) {
        console.log("Latitude is :", position.coords.latitude);
        console.log("Longitude is :", position.coords.longitude);

        var lat = position.coords.latitude;
        var lon = position.coords.longitude;

        const url = `http://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&units=metric&appid=ca148f5dc67f12aafaa56d1878bb6db2`;
        const response = await fetch(url);
        let data = await response.json();
        
        console.log(data);
        this.setState(data);
      });
    }
  }
1个回答

this范围已经改变。您需要使用箭头函数或将 分配给this另一个变量。你可以改变 -

navigator.geolocation.watchPosition(async (position) => {
    // Your code here...
});

否则,您可以将this变量保留到外部作用域的另一个变量中并在内部使用。

componentDidMount() {
    if (navigator.geolocation) {
        // Keep the this to the self variable.
        const self = this;
        navigator.geolocation.watchPosition(async function (position) {
            // The other codes...
            self.setState(data);
        });
    }
}