使用useEffect调用API获取客户时构建报错:Property 'data' does not exist on type 'void'
问题:构建时出现“Property 'data' does not exist on type 'void'”错误
本地使用useEffect调用API获取客户数据正常,但执行构建时触发以下错误:
"message": "Property 'data' does not exist on type 'void"
相关代码片段:
useEffect(() => { const fetchCustomers = async () => { try { const res = await auth.getcustomer({ name: '', orgId: '', entryId: '', id: ''}); console.log('response in use effect: ', res.data.data.customers); setData(transformData(res.data.data.customers)); return res; } catch (error) { console.error('Error fetching customers:', error); return null; } }; const fetchData = async () => { const result = await fetchCustomers(); if (result) { } else { } }; fetchData(); }, [auth]);
API定义:
const handleGetCustomer = ( params: GetCustomerParams, errorCallback?: ErrCallbackType ) => { return axios .post(authConfig.getcustomerEndPoint, params, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${globalToken}`, }, }) };
参数类型:
export type GetCustomerParams = { name: string entryId: string orgId: string id:string }
解决方案
核心原因
TypeScript无法正确推断auth.getcustomer的返回类型,默认将其视为void,因此访问res.data时触发类型错误。本质是API函数缺少明确的类型定义,导致类型推断失效。
具体修复步骤
定义API响应类型
先明确接口返回的数据结构,示例:// 定义单条客户数据结构 export type Customer = { id: string; name: string; // 补充实际返回的其他字段 }; // 定义API整体响应结构 export type GetCustomerResponse = { data: { customers: Customer[]; }; };给API函数指定返回类型
修改handleGetCustomer,明确返回AxiosResponse包裹的响应类型:import { AxiosResponse } from 'axios'; const handleGetCustomer = ( params: GetCustomerParams, errorCallback?: ErrCallbackType ): Promise<AxiosResponse<GetCustomerResponse>> => { return axios .post<GetCustomerResponse>(authConfig.getcustomerEndPoint, params, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${globalToken}`, }, }) };注意给
axios.post添加泛型参数<GetCustomerResponse>,让Axios正确推断响应数据类型。确保auth对象类型正确
如果auth是自定义对象,给它定义类型确保getcustomer属性与API函数类型一致:export type AuthService = { getcustomer: typeof handleGetCustomer; // 补充auth对象的其他方法类型 }; // 给auth实例指定类型 const auth: AuthService = { getcustomer: handleGetCustomer, // ...其他方法 };可选:显式指定res的类型
若上述步骤后仍有问题,可在fetchCustomers中给res强制指定类型:const res = await auth.getcustomer(...) as AxiosResponse<GetCustomerResponse>;
内容的提问来源于stack exchange,提问作者Hazal Kaya
相关产品推荐
相关产品推荐

