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

ReactJS报错:Cannot read properties of undefined (reading 'then') 求助

解决React中Cannot read properties of undefined (reading 'then')错误

错误原因

你遇到的核心问题是EmployeeService.getEmployees()方法没有返回任何值(默认返回undefined),而你试图在它后面调用.then()方法——只有Promise对象才有.then()方法,所以会抛出"Cannot read properties of undefined (reading 'then')"的错误。

解决方案

1. 修复EmployeeService.js的getEmployees方法

在getEmployees方法中返回axios发起请求后的Promise对象,修改后的代码如下:

import axios from "axios";

// 注意:需确认后端接口路径,示例中补充了/employees,根据实际情况调整
const EMPLOYEES_REST_API_URL = "http://localhost:8080/employees";

class EmployeeService {
    getEmployees() {
        // 关键:添加return,返回axios请求的Promise
        return axios.get(EMPLOYEES_REST_API_URL);
    }
}

export default new EmployeeService();

2. (可选)添加错误处理

为避免请求失败导致页面异常,建议在componentDidMount中添加.catch()捕获错误:

componentDidMount() {
    EmployeeService.getEmployees()
        .then((response) => {
            this.setState({ employees: response.data });
        })
        .catch(error => {
            console.error("获取员工数据失败:", error);
            // 可在此添加错误提示逻辑,比如设置state显示错误信息
        });
}

3. 验证API地址正确性

确认你的后端服务在http://localhost:8080正常运行,且目标接口(比如/employees)能返回正确的员工列表数据,若教程中接口路径不同,需对应修改EMPLOYEES_REST_API_URL的值。

补充说明

你之前调整的导出方式(实例化类后导出)是正确的,问题根源不在导出逻辑,而是getEmployees方法未返回Promise对象。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 01:23:35