You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中Cannot read properties of undefined (reading 'getWeather')错误求助

React天气应用报错:Cannot read properties of undefined (reading 'getWeather')

我正在使用ReactJS开发一款天气应用,以下是我的代码:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      temp: ""
    };
    this.getLocation = this.getLocation.bind(this);
    this.getWeather = this.getWeather.bind(this);
  }
  componentDidMount() {
    this.getLocation();
  }
  getLocation() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(success,error);
    }
    else {
      console.log("Not supported");
    }
    function success(position) {
      lat = position.coords.latitude;
      lon = position.coords.longitude;
      console.log(lat,lon);
      this.getWeather();
    }
    function error() {
      console.log("Unable to retrieve your location");
    }
  }
  getWeather() {
    fetch(`http://api.weatherapi.com/v1/current.json?key=${api}&q=${lat},${lon}&aqi=no`)
    .then((data) => data.json())
    .then((item) => {
      console.log(item);
    });
  }
}

其中api、lat和lon是我在此之前声明并初始化的常量,当前出现如下错误:

Cannot read properties of undefined (reading 'getWeather')
    at success

问题原因

success回调函数内部的this指向不是组件实例,而是全局对象(浏览器环境下为window),因此调用this.getWeather()时会找不到该方法,触发报错。

解决方法

有三种常用修复方式:

1. 用箭头函数定义回调

箭头函数会继承外层作用域的this(即组件实例),直接解决指向问题:

getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
      (position) => {
        lat = position.coords.latitude;
        lon = position.coords.longitude;
        console.log(lat, lon);
        this.getWeather();
      },
      () => {
        console.log("Unable to retrieve your location");
      }
    );
  } else {
    console.log("Not supported");
  }
}

2. 提前保存组件实例的this

在getLocation函数开头定义变量存储组件的this,回调中用该变量替代this:

getLocation() {
  const self = this;
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(success, error);
  } else {
    console.log("Not supported");
  }
  function success(position) {
    lat = position.coords.latitude;
    lon = position.coords.longitude;
    console.log(lat, lon);
    self.getWeather();
  }
  function error() {
    console.log("Unable to retrieve your location");
  }
}

3. 绑定回调函数的this

通过bind方法将组件实例绑定到success函数上,强制修改其内部this指向:

getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(success.bind(this), error);
  } else {
    console.log("Not supported");
  }
  function success(position) {
    lat = position.coords.latitude;
    lon = position.coords.longitude;
    console.log(lat, lon);
    this.getWeather();
  }
  function error() {
    console.log("Unable to retrieve your location");
  }
}

额外建议:当前lat和lon为全局变量,建议改为组件状态(this.state)或实例属性(this.lat/this.lon),避免全局变量污染。

内容的提问来源于stack exchange,提问作者Arslan Asad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 23:08:23