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

TypeScript报错:AxiosResponse与countries[]类型不匹配如何解决

报错原因

  • 你调用axios.get拿到的res是Axios封装的响应对象,里面包含状态码、响应头、响应数据等多类信息,并不是接口直接返回的国家数组,数组实际存放在res.data字段里,你直接把整个res赋值给声明为countries[]类型的countries状态,类型完全不匹配才会触发该报错。
  • 你没有给axios.get显式指定响应数据的类型,TS无法自动推导res.data的结构,需要通过泛型声明类型。

修正步骤

  1. 先修正现有类型定义的笔误:把countries接口里的astring改为string,建议同时将接口名改为大驼峰Country(符合TS命名规范,避免和数组变量名混淆)
  2. 给axios.get添加泛型声明,指定响应返回的data类型为Country[]
  3. 赋值时取res.data而非整个res

修正后完整代码

export interface IProfileEditorState {
  countries: Country[];
  error?: any;
  isLoading?: boolean;
}

// 接口名改为大驼峰更规范
interface Country {
  countryID: string;
  countryName: string;
  label: string; // 修正笔误astring为string
  value: string;
  isDirector: number;
}

// Temp
public getCountrys() {
  axios
  // 泛型指定响应data的类型为Country[]
  .get<Country[]>('https://func-myportal-dev.azurewebsites.net/api/GetCountries?code=j0xGK8L6iRXpZqR3DgaDRoI/H/qjGZSGdBPIY9rZU84uH4SUa80noQ==')
  .then(res => {
   // 取res.data赋值,而非整个res
   this.setState({countries: res.data});
  })
  // Error catching
  .catch(error => this.setState({ error, isLoading: false }));
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 05:27:00