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

React自定义hook useGetPokemon解构返回值为undefined问题排查

核心原因

你遇到的问题是因为错误地给自定义Hook添加了async声明:

  • async函数的返回值会默认被包装为Promise实例,你在useGetPokemon内部return的{fetchPokemon, pokemon, error}对象,实际是Promise resolve后的值,不是useGetPokemon()调用的直接返回结果。
  • 你在组件中调用useGetPokemon()拿到的是一个Promise对象,对不存在fetchPokemon属性的Promise进行解构,自然得到undefined。

修复方案

直接删除useGetPokemon外层的async关键字即可,外层Hook本身不需要异步声明,异步逻辑已经封装在内部的fetchPokemon函数中。

修复后的自定义Hook代码:

const useGetPokemon = () => {
  const [pokemon, setPokemon] = useState(null);
  const [fetchError, setFetchError] = useState(null);
  const { clearErrors } = useForm();

  const fetchPokemon = async (input) => {
    input = input.toLowerCase();

    try {
      const res = await axios.get(`https://pokeapi.co/api/v2/pokemon/${input}`);
      const { data } = res;

      if (data) {
        setPokemon(data);
        setFetchError(null);
        clearErrors();
      }
    } catch (error) {
      setPokemon(null);
      setFetchError(error);
    }
  };

  return { fetchPokemon, pokemon, error: fetchError };
};

修复后组件中调用useGetPokemon()会直接返回你定义的普通对象,解构即可拿到正常的fetchPokemon函数,防抖逻辑也可以正常运行。

补充说明

这是React自定义Hook的基础规则:所有自定义Hook本质都是普通同步函数,内部可以封装异步逻辑,但Hook本身不能被声明为async,否则返回值会被Promise包装,无法直接拿到预期的返回属性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 10:45:03