React 中无法调用 ‘then’ 函数的常见原因及修复方法

本文详解 react 组件中因拼写错误(如将 `this` 误写为 `then`)导致 `.then is not a function` 报错的问题,并提供完整修复方案、最佳实践与注意事项。

在使用 axios 等 Promise-based API 从后端(如 Django)获取数据时,React 开发者常遇到类似 TypeError: then.setState is not a function 的报错。该错误并非 React 或 axios 的兼容性问题,而是典型的 JavaScript 拼写错误所致。

回顾原始代码中的关键片段:

componentNotesData() {
  let data;
  axios.get('http://127.0.0.1:8000/')
    .then(res => {
      data = res.data;
      then.setState({  // ❌ 错误:'then' 是未声明变量,非关键字,也非 this 的别名
        notes: data
      });
    })
    .catch(err => {});
}

此处 then.setState(...) 中的 then 是一个未定义的标识符(ReferenceError),JavaScript 尝试访问其 setState 属性时自然抛出 then.setState is not a function —— 实际上它连对象都不是。正确写法应为 this.setState(...),因为 setState 是 React 类组件实例(即 this)上的方法。

✅ 正确修复后的 componentNotesData 方法如下:

componentNotesData() {
  axios.get('http://127.0.0.1:8000/')
    .then(res => {
      this.setState({
        notes: res.data // 直接使用 res.data,无需中间变量
      });
    })
    .catch(err => {
      console.error('Failed to fetch notes:', err); // 建议添加错误日志
    });
}

⚠️ 还需注意以下关键点:

  • 生命周期调用缺失:当前 componentNotesData() 未在任何生命周期钩子中被调用(如 componentDidMount),因此数据永远不会加载。应在挂载后触发请求:

    componentDidMount() {
      this.componentNotesData();
    }
  • 空数组渲染报错风险:render() 中直接调用 this.state.notes.map(...),若 notes 初始为空数组则无问题;但若 notes 为 null 或 undefined(例如初始状态未设或接口返回异常结构),会触发 Cannot read property 'map' of null。建议增加防御性检查:

    render() {
      const { notes } = this.state;
      return (
        
          {Array.isArray(notes) && notes.length > 0 ? (
            notes.map((note, index) => (
               {/* ✅ 必须添加 key */}
                

    {note.title}

    )) ) : (

    Loading notes...

    )} ); }
  • 现代替代方案推荐:类组件已逐渐被函数组件 + useState/useEffect 取代。更简洁、不易出错的写法如下(推荐用于新项目):

    import React, { useState, useEffect } from 'react';
    import axios from 'axios';
    
    function App() {
      const [notes, setNotes] = useState([]);
    
      useEffect(() => {
        axios.get('http://127.0.0.1:8000/')
          .then(res => setNotes(res.data))
          .catch(err => console.error('Fetch failed:', err));
      }, []);
    
      return (
        
          {notes.map((note, index) => (
            
              

    {note.title}

    ))} ); } export default App;

? 总结:then.setState is not a function 这类报错几乎总是源于 this 的拼写错误(如 than、then、thi 等)。借助编辑器语法高亮、ESLint(推荐配置 eslint-plugin-react 和 no-invalid-this 规则)及开启严格模式("use strict"),可大幅降低此类低级错误发生概率。开发中养成「先查拼写,再查逻辑」的习惯,能快速定位并解决 80% 的类似问题。