Axios响应类型报错:'AxiosResponse<IUser, any>'非数组类型求助
问题分析与解决
1. 核心错误:误用Axios响应对象
你遇到的报错'Type 'AxiosResponse<IUser, any>' is not an array type',本质是**getProfileById返回了完整的Axios响应对象,而非接口返回的实际用户数据**。Axios的get方法返回的response是包含data、status等属性的对象,其中response.data才是API返回的用户资料实体。
修复方法:修改getProfileById返回response.data
static async getProfileById(id: string | undefined){ const jwt = localStorage.getItem("jwt"); const response = await axios.get<IUser>(`http://localhost:4000/api/feed/id?id=${id}`, { headers: { authorization: "Bearer " + jwt } }) // 返回API返回的实际用户数据,而非整个Axios响应 return response.data; }
2. 接口类型笔误修正
你当前复用IPost接口却标注为IUser,会导致类型不匹配。需根据API返回的用户资料结构,定义正确的IUser接口:
// 示例,根据你的API实际返回字段调整 export interface IUser { _id: string; username: string; avatar?: string; // 其他用户相关字段... }
3. 循环中状态更新的优化
原循环存在两个问题:
- 试图用扩展运算符
...profileSub添加单个用户,但profileSub是单个IUser对象,无需用...; - 异步循环中直接依赖
subs旧值更新状态,会导致状态更新不及时,需用函数式更新确保获取最新状态。
修复后的循环代码
for (let i = 0; i < response.length; i++){ // 过滤无效ID,避免传入undefined if (!response[i]) continue; const profileSub = await UserService.getProfileById(response[i]); // 函数式更新,基于最新状态添加新用户 setSubs(prevSubs => [...prevSubs, profileSub]); }
内容的提问来源于stack exchange,提问作者stephaniex
相关产品推荐
相关产品推荐

