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

React项目中传入setState后服务方法state参数仍为undefined问题

问题原因分析

核心问题:函数名拼写不一致

你在API服务中导出的函数名为 getProductCustoumer(注意拼写:Custoumer,中间多了一个字母u),但在组件的useEffect中调用的是 getProductCustomer(正确拼写:Customer)。

这种拼写错误会导致:

  • 你实际调用的并不是你定义的那个带有state参数的函数(如果项目中没有其他同名的getProductCustomer函数,控制台应该还会报“函数未定义”的错误)
  • 即使存在其他同名函数,也会因为参数不匹配,导致当前你写的这个getProductCustoumer函数根本没被执行,自然其中的state参数会是undefined。

其他优化点(非直接原因,但建议修正)

  1. 避免await和.then混用:API服务中的代码可以简化,无需在await后再用.then,同时可以用可选链避免state未传入时报错:
export const getProductCustomer = async (customerid, state) => {
  const result = await api.get(`ProductCustomer?customerid=${customerid}`);
  const data = result.data;
  state?.(data);
  return data;
};
  1. 组件中无需重复调用setData:因为服务函数已经会调用state(data),组件里拿到返回值后再调用setData(response)属于重复操作,直接去掉即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 01:13:18