首页 > 解决方案 > 从 useEffect 返回承诺

问题描述

我正在阅读文章https://www.robinwieruch.de/react-hooks-fetch-data

它提供了以下 2 个片段来演示如何处理 useEffect 中的承诺。第一个会引发错误,而第二个不会。

第一个片段 -

  useEffect(async () => {
    const result = await axios(
      'https://hn.algolia.com/api/v1/search?query=redux',
    );
 
    setData(result.data);
  }, []);

第二个片段 -

useEffect(() => {
    const fetchData = async () => {
      const result = await axios(
        'https://hn.algolia.com/api/v1/search?query=redux',
      );
 
      setData(result.data);
    };
 
    fetchData();
  }, []);

为什么第二个不抛出错误,当fetchdata()被调用时它会返回一个promise,因此也会返回一个promise useEffect。第二个片段与第一个片段有何不同?

标签: reactjsreact-hooks

解决方案


You can only return nothing or a cleanup function for useEffect hook. The reason the first snippet is throwing an error is because you marked the function async and the functions that are marked async will always return a promise.

//The function is marked async
 useEffect(async () => {
    const result = await axios(
      'https://hn.algolia.com/api/v1/search?query=redux',
    );
 
    setData(result.data);
  }, []);

It breaks the rule of returning either nothing or a cleanup function.

However In the second snippet, you are using useEffect function to call an async function, but since the useEffect function itself is not async, that means it is not returning a promise

//this is not marked async
  useEffect(() => {
    const fetchData = async () => {
      const result = await axios(
        'https://hn.algolia.com/api/v1/search?query=redux',
      );
 
      setData(result.data);
    };
 
    fetchData();
  }, []);

推荐阅读