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

React类组件调用API时报错this.setState is not a function怎么解决?

错误原因及修复方案
  • 错误1:构造函数中错误覆盖了内置setState方法
    你在constructor中错误地把this.setState赋值成了状态对象,直接覆盖了React类组件内置的setState方法,这是触发报错的直接原因。
    错误写法:
    this.setState = {posts: []}
    
    正确写法是给this.state赋值初始化状态:
    this.state = {posts: []}
    
  • 错误2:getPost方法未绑定组件实例this指向
    类组件中声明的普通方法默认不会绑定this指向组件实例,在fetch的异步回调中调用this.setState时,this无法指向组件实例,就算修复了第一个问题也会触发undefined相关报错。
    修复方案有两种可选:
    1. 在constructor中手动绑定this:
    constructor(props){
      super(props);
      this.state = {posts: []}
      this.getPost = this.getPost.bind(this)
    }
    
    1. 直接把getPost改成箭头函数,自动绑定this:
    getPost = () => {
      // 原有逻辑
    }
    
  • 错误3:接口返回结果解构错误
    你调用的接口直接返回的是帖子数组,不存在外层包裹的data属性,你用({data}) =>解构会拿到undefined,无法正确赋值给posts。
    正确写法是直接接收返回的数组:
    .then(data => this.setState({ posts: data }))
    

修正后完整代码

import React from 'react';
class Post extends React.Component {
  constructor(props){
    super(props);
    this.state = {posts: []}
    this.getPost = this.getPost.bind(this)
  }
  componentDidMount(){
    this.getPost();
  }
  getPost(){
    fetch('https://jsonplaceholder.typicode.com/posts')
    .then(response => response.json())
    .then(data => this.setState({ posts: data }));
  }
  render(){
   return (
         <div>
           <h2>Post</h2>
         </div>
      )
  }
}
export default Post;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 03:30:03