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

TypeScript报错:Property 'data'不存在于指定Promise类型,如何解决?

解决TypeScript中Axios请求后访问data属性的报错问题

错误根源

你的代码中,axios.post后链式调用了.catch(),但catch回调仅执行console.log且无返回值,导致该Promise的类型变为Promise<void | AxiosResponse<{ data: { email: string; username: string } }>>。当await res后,res可能是void(请求失败时),自然无法访问data属性。

解决方案

方案1:用try/catch替代链式catch

这种方式能明确保证请求成功时res为AxiosResponse类型,失败逻辑集中在catch块处理:

const sendRequest = async (params: LoginProps) => {
  try {
    // 泛型直接指定响应data的类型更简洁
    const res = await axios.post<{ email: string; username: string }>(
      'http://localhost:3333',
      { ...params }
    );
    return res.data;
  } catch (err) {
    console.log('errors', err);
    // 可根据需求返回默认值或抛出错误
    // 示例:return { email: '', username: '' };
    // 或:throw err;
  }
};

方案2:链式catch中返回有效结构或重新抛错

若坚持链式调用,需确保catch回调返回符合AxiosResponse结构的默认值,或重新抛出错误,避免Promise类型包含void:

示例1:返回默认响应结构
const sendRequest = async (params: LoginProps) => {
  const res = await axios.post<{ email: string; username: string }>(
    'http://localhost:3333',
    { ...params }
  ).catch((err) => {
    console.log('errors', err);
    return { data: { email: '', username: '' } };
  });

  return res.data;
};
示例2:重新抛出错误(需调用方处理)
const sendRequest = async (params: LoginProps) => {
  const res = await axios.post<{ email: string; username: string }>(
    'http://localhost:3333',
    { ...params }
  ).catch((err) => {
    console.log('errors', err);
    throw err; // 确保res始终为AxiosResponse类型
  });

  return res.data;
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 02:20:33