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

React调用PostService报Cannot read 'then' of undefined错误如何解决

问题修复方案

错误根因

  • PostService类中getPosts()方法没有返回axios.get()执行后的Promise对象,方法默认返回undefined,因此在componentDidMount中调用.then()时触发Cannot read properties of undefined (reading 'then')类型错误。

修复方法

1. 核心修复

修改PostService的getPosts()方法,添加return关键字返回axios请求的Promise对象,修改后代码如下:

import axios from "axios";

const POST_API_BASE_URL = "http://localhost:8080/api/posts";

class PostService {
    getPosts() {
        // 新增return返回Promise
        return axios.get(POST_API_BASE_URL);
    }
}

export default new PostService();

2. 可选优化

建议补充请求异常捕获逻辑,避免接口请求失败时页面抛出未捕获错误:

componentDidMount(){
  PostService.getPosts()
    .then((response) => {
      this.setState({ posts: response.data });
    })
    .catch(err => {
      console.error('帖子列表请求失败:', err);
      // 可自定义错误提示、兜底数据设置等逻辑
    });
}

另外你代码中表格的类名table-boarded拼写有误,若使用Bootstrap样式,对应的正确边框类名为table-bordered,可按需修正。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 13:24:03