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

React报错:Cannot read property 'state' of undefined 问题求助

解决React中fetch回调里Cannot read property 'state' of undefined的问题

嘿,这个问题我之前开发React类组件时也踩过坑!核心原因就是fetch的回调函数里的this没有指向你的App组件实例,自然就访问不到this.state了。下面给你几个简单可行的解决办法:

方法1:用箭头函数(最推荐,写法简洁)

箭头函数会自动继承外层作用域的this,所以在.then()里用箭头函数就能直接拿到组件的this:

componentWillMount() {
  fetch('https://randomuser.me/api/')
    .then(response => response.json())
    .then(data => {
      // 这里的this就是App组件实例啦
      this.setState({
        pictures: data.results.map(person => person.picture.large),
        people: data.results.map(person => person.name.first)
      });
    })
    .catch(error => console.error('请求出错啦:', error));
}

方法2:提前存好this的引用

在fetch之前把组件的this存到一个变量(比如that或者self)里,之后在回调里用这个变量代替this:

componentWillMount() {
  const that = this; // 先把组件的this存起来
  fetch('https://randomuser.me/api/')
    .then(function(response) {
      return response.json();
    })
    .then(function(data) {
      // 用that代替this,就能访问到state了
      that.setState({
        pictures: data.results.map(person => person.picture.large),
        people: data.results.map(person => person.name.first)
      });
    })
    .catch(error => console.error('请求出错啦:', error));
}

方法3:给回调函数bind绑定this

手动给每个.then()里的回调函数绑定组件的this,确保this指向正确:

componentWillMount() {
  fetch('https://randomuser.me/api/')
    .then(function(response) {
      return response.json();
    }.bind(this)) // 绑定this
    .then(function(data) {
      this.setState({
        pictures: data.results.map(person => person.picture.large),
        people: data.results.map(person => person.name.first)
      });
    }.bind(this)) // 绑定this
    .catch(error => console.error('请求出错啦:', error));
}

另外给你提个小建议:componentWillMount在React 16.3版本之后已经被标记为过时API了,推荐用componentDidMount来发起数据请求——它只会在组件挂载完成后执行一次,不会像componentWillMount那样可能在服务端渲染时被多次调用,更适合做数据请求这类操作。

最后给你一个修改后的完整组件示例,直接用就能跑:

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  constructor(){
    super();
    this.state = {
      pictures: [],
      people: [],
    };
  }

  componentDidMount() {
    fetch('https://randomuser.me/api/')
      .then(response => response.json())
      .then(data => {
        this.setState({
          pictures: data.results.map(item => item.picture.large),
          people: data.results.map(item => item.name.first)
        });
      })
      .catch(err => console.log('请求失败:', err));
  }

  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <div className="App-intro">
          {/* 渲染拿到的名字和照片 */}
          {this.state.people.map((name, index) => (
            <div key={index} style={{margin: '10px 0'}}>
              <p>{name}</p>
              <img src={this.state.pictures[index]} alt={name} style={{borderRadius: '50%'}} />
            </div>
          ))}
        </div>
      </div>
    );
  }
}

export default App;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:13:28