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

TypeScript中React类组件axios回调内调用setState报this错误如何解决

问题根因

  • axios.get的then回调使用了普通函数声明,普通函数会创建独立的this绑定,遮蔽了外层指向React组件实例的this,TypeScript无法确定当前this的类型,因此抛出报错。
  • 你定义的State类型存在语法错误:重复声明了fetchedPassword字段,缺少fetchedUsername字段的定义。
  • 类组件继承语法错误:extends React.Component<Props,State>()末尾多了多余的括号,需要删除。

修复方案

方案1(推荐):将回调替换为箭头函数

箭头函数不会创建独立的this绑定,会直接继承外层作用域的this(即组件实例),是最常用的修复方式:

authLogin = (e:any) => {
  e.preventDefault();
  const { fetchedUsername, fetchedPassword } = this.state;

  axios
    .get(url)
    // 把普通函数改为箭头函数
    .then((response) => {
      // 可合并为一次setState调用,减少重渲染次数
      this.setState({
        fetchedPassword: response.data.password,
        fetchedUsername: response.data.username
      });
    })
    // catch也同步改为箭头函数,避免后续用到this时同样报错
    .catch((error) => {
      console.log("Error: " + error);
    });
}

方案2:提前缓存this引用

如果需要保留普通函数写法,可以在外层预先保存组件实例的引用:

authLogin = (e:any) => {
  e.preventDefault();
  const { fetchedUsername, fetchedPassword } = this.state;
  // 提前缓存组件实例的this
  const componentInstance = this;

  axios
    .get(url)
    .then(function (response) {
      componentInstance.setState({
        fetchedPassword: response.data.password,
        fetchedUsername: response.data.username
      });
    })
    .catch(function (error) {
      console.log("Error: " + error);
    });
}

同步修复前置语法错误

// 修复State类型字段错误
type State = {
  fetchedPassword: string;
  fetchedUsername: string;
}

type Props = {}

// 去掉继承语法末尾多余的括号
export default class MyComponent extends React.Component<Props,State> {
  // constructor等原有逻辑保持不变即可
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 13:39:00