React报错TypeError:无法解构未定义中间值的‘data’属性
解决:TypeError: Cannot destructure property 'data' of '(intermediate value)' as it is undefined
错误核心原因
这个错误直接指向你在解构某个中间值的data属性时,该值为undefined。结合你的场景,本质是**fetchCategories函数没有返回预期的Axios响应对象**——要么是函数漏写了返回语句,要么是请求失败未被处理,最终导致await fetchCategories()拿到的是undefined。
具体解决步骤
1. 修复fetchCategories的返回逻辑
检查你的Axios请求函数,确保它返回了请求的Promise。很多时候会漏写return,导致函数默认返回undefined:
// 错误写法:无return,函数返回undefined const fetchCategories = async () => { axiosInstance.get('/api/categories') } // 正确写法:返回Axios请求的Promise const fetchCategories = async () => { return axiosInstance.get('/api/categories') }
2. 给请求添加错误捕获
Axios请求可能因网络问题、接口报错等失败,未处理的错误会导致Promise reject,进而让解构操作拿到undefined。在getServerSideProps里用try/catch兜底:
export async function getServerSideProps() { try { // 确保fetchCategories返回有效响应后再解构 const { data } = await fetchCategories(); return { props: { categories: data as ICategory[] } }; } catch (error) { console.error('获取分类列表失败:', error); // 返回默认值避免页面崩溃 return { props: { categories: [] as ICategory[] } }; } }
3. 验证Axios实例与接口响应
- 检查Axios实例的
baseURL、请求头(如token、Content-Type)是否配置正确,确保能正常访问目标接口; - 在
fetchCategories里打印响应,确认接口返回格式是否符合预期:const fetchCategories = async () => { const response = await axiosInstance.get('/api/categories'); console.log('接口原始响应:', response); // 确认response.data是否存在 return response; }
4. 对齐TypeScript接口与实际响应结构
如果你的接口返回嵌套格式(比如{ code: 200, data: ICategory[] }),要注意解构层级:
// 假设接口返回格式为 { code: number, data: ICategory[] } const response = await fetchCategories(); const { data: categories } = response.data; // 先取外层data,再拿分类数据
内容的提问来源于stack exchange,提问作者Znaneswar
相关产品推荐
相关产品推荐

