调用POST API报错:Property 'post'不存在于AxiosInstance生成函数类型
解决“Property 'post' does not exist on type '(optionalToken?: string | undefined) => AxiosInstance'”错误
问题原因
fetchClient不是直接的Axios实例,而是一个返回Axios实例的工厂函数。你直接调用它的.post方法,相当于在函数对象上查找不存在的属性,因此触发类型错误。
解决方案
先调用fetchClient函数获取Axios实例,再调用.post方法:
无需传入token的情况
const addUserSeviceExpertHours = async () => { try { const response = await fetchClient().post(API.ADD_USERSERVICE_EXPERT_HOURS, { ProducId: cartData?.productID, Amount: (limitExceedHours * cartData.unitRate + tax).toFixed(2), Hours: limitExceedHours, ProductDescription: 'expert-hour', }); return response; } catch (error) { return error as Error; } };
需要传入token的情况
如果fetchClient需要token参数生成带授权的实例,直接传入即可:
const addUserSeviceExpertHours = async () => { // 替换为实际的有效token const authToken = "your-valid-token"; try { const response = await fetchClient(authToken).post(API.ADD_USERSERVICE_EXPERT_HOURS, { ProducId: cartData?.productID, Amount: (limitExceedHours * cartData.unitRate + tax).toFixed(2), Hours: limitExceedHours, ProductDescription: 'expert-hour', }); return response; } catch (error) { return error as Error; } };
额外优化说明
原代码同时使用await和.then()属于冗余写法,改用try/catch结构更符合async/await的编码习惯,代码可读性更强。
内容的提问来源于stack exchange,提问作者Numan Aziz
相关产品推荐
相关产品推荐

