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

React类组件中setProgress函数未定义报错问题求助

解决TypeError: this.setProgress is not a function的问题

这个报错主要有两个核心原因,咱们一步步拆解解决:

1. 错误调用了未定义的this.setProgress

在你的News组件updateNews方法的第一行,你写了:

this.setProgress(10);

但实际上setProgress是父组件App通过props传递过来的方法,必须通过this.props来访问它,所以这行要改成:

this.props.setProgress(10);

你后面的代码里已经正确使用了this.props.setProgress,只有第一行漏写了props,这是触发报错的直接原因之一。

2. 确保updateNews方法的this指向正确

类组件中的普通方法(非箭头函数定义)默认不会绑定组件实例的this,当你在componentDidMount里调用this.updateNews()时,方法内部的this可能会指向undefined,这也会导致类似的函数不存在报错。这里有三种常用的解决方式:

方式一:用箭头函数定义updateNews

把updateNews改成箭头函数形式,它会自动继承类实例的this:

updateNews = async () => {
  this.props.setProgress(10);
  // 剩下的业务逻辑代码保持不变
}

方式二:在构造函数中手动绑定this

在News组件的构造函数里,给updateNews绑定组件实例的this:

constructor(props) {
  super(props);
  // 初始化组件必要的state
  this.state = {
    articles: [],
    page: 1,
    loading: false,
    totalResults: 0
  };
  this.updateNews = this.updateNews.bind(this);
}

方式三:调用时通过箭头函数指定this

在componentDidMount里调用updateNews时,用箭头函数包裹来确保this指向正确:

componentDidMount() {
  (() => this.updateNews())();
}

额外检查:修复App组件的代码完整性

你的App组件代码存在标签闭合和结构问题,需要确保JSX都包裹在render方法内,并且标签正确闭合:

export default class App extends Component {
  pageSize = 5; // 假设你定义了这个分页变量
  state = {
    progress: 0
  }

  setProgress = (progress) => {
    this.setState({ progress: progress });
  }

  render() {
    return (
      <Router>
        <NavBar />
        <LoadingBar progress={this.state.progress} />
        <Routes>
          <Route path="/" element={<News progress={this.setProgress} key="General" pageSize={this.pageSize} country={'in'} category={'General'} />} exact />
          {/* 其他路由规则可以在这里添加 */}
        </Routes>
      </Router>
    );
  }
}

注意原代码里的<Routes/>和<Router/>是错误写法,要改成闭合标签</Routes>和</Router>。

完成以上所有修改后,你的报错应该就能彻底解决了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 10:05:24