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
相关产品推荐
相关产品推荐

