基于TypeScript、React和React-Query处理Axios错误响应问题
解决TypeScript错误:Property 'message' does not exist on type 'MyErrorResponse'
问题原因
你的MyErrorResponse类型仅定义了errors数组(每个元素包含detail字段),但组件代码中尝试访问error.response?.data.message——该属性未在类型中声明,因此TypeScript抛出错误。同时你需要实现:优先显示错误消息,无可用消息时默认展示错误状态码。
解决方案
1. 调整组件代码匹配现有类型
如果API始终以errors数组格式返回错误信息,直接访问errors中的detail字段,并在无可用消息时回退到状态码:
const { mutate, error } = useLogin() {error && ( <Typography variant='h6' sx={{ color: theme.palette.red, mt: 2 }}> {error.response?.data.errors[0]?.detail || `错误状态码:${error.response?.status || '未知'}`} </Typography> )}
2. 更新类型兼容多种错误格式
如果API可能返回message字段(而非errors数组),将MyErrorResponse扩展为联合类型,并在组件中处理两种情况:
修改auth service中的类型定义:
type MyErrorResponse = | { errors: { detail: string }[] } | { message: string };
组件中处理两种错误格式:
const { mutate, error } = useLogin() const getErrorMessage = () => { if (!error?.response?.data) return `错误状态码:${error?.response?.status || '未知'}`; const errorData = error.response.data; if ('message' in errorData) { return errorData.message; } return errorData.errors[0]?.detail || `错误状态码:${error?.response?.status || '未知'}`; }; {error && ( <Typography variant='h6' sx={{ color: theme.palette.red, mt: 2 }}> {getErrorMessage()} </Typography> )}
关键说明
- 使用可选链操作符(
?.)避免空值报错,因为error.response或errors[0]可能不存在。 - 回退逻辑确保即使没有具体错误消息,用户也能获得状态码作为提示。
内容的提问来源于stack exchange,提问作者Joseph
相关产品推荐
相关产品推荐

