Next.js14+TS+React-Query中useMutation类型不匹配问题求助
技术栈:Next.js 14、TypeScript、react-query
现有代码结构:
- API客户端类
APIClient的post方法包含try-catch结构 - 登录钩子代码:
export const useLogin = () => useMutation<ILoginResponse, AxiosError<any>, ILoginInput>(loginService.post);
- 登录表单通过
handleLogin调用mutateAsync
当前遇到的类型错误:
No overload matches this call. The last overload gave the following error. Argument of type '(data: U) => unknown' is not assignable to parameter of type 'MutationKey'.ts(2769)
且仅当post方法包含try-catch时才会触发该错误,已尝试调整MutationKey、修改try-catch结构但无效。
问题原因
当APIClient.post方法包含try-catch时,TypeScript无法正确推导该函数的返回值类型,导致返回值被推断为unknown。而react-query的useMutation期望第一个参数是返回Promise<ILoginResponse>的函数,类型不匹配触发了错误。
核心是try-catch块未明确返回类型,或catch分支的处理让TypeScript无法确定函数的返回类型,最终把返回值推断为unknown,不符合useMutation的类型要求。
解决方案
方案1:给APIClient.post明确指定泛型返回类型
通过显式声明返回类型,让TypeScript精准识别函数的返回值:
class APIClient { async post<T>(url: string, data: any): Promise<T> { try { const response = await axios.post<T>(url, data); return response.data; } catch (error) { // 统一处理错误并抛出,保证类型一致性 if (axios.isAxiosError(error)) { throw error; } throw new Error('请求失败'); } } } const loginService = new APIClient();
方案2:在useMutation中包装loginService.post
如果不想修改APIClient类,用箭头函数包装调用逻辑,明确参数和返回值类型:
export const useLogin = () => useMutation<ILoginResponse, AxiosError<any>, ILoginInput>( (input: ILoginInput) => loginService.post<ILoginResponse>('/api/login', input) );
方案3:确保catch分支始终抛出错误
若catch分支未抛出错误,函数可能返回undefined,导致类型推断异常。必须保证catch分支要么抛出错误,要么返回符合类型要求的值:
async post<T>(url: string, data: any): Promise<T> { try { const response = await axios.post<T>(url, data); return response.data; } catch (error) { // 必须抛出错误,避免函数返回undefined throw error; } }
内容的提问来源于stack exchange,提问作者Valhalla Gonzo

