useEffect 中异步函数的 React Hook 警告:useEffect 函数必须 return 清理函数或什么都不做

React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing

我正在尝试下面的 useEffect 示例:

useEffect(async () => {
    try {
        const response = await fetch(`https://www.reddit.com/r/${subreddit}.json`);
        const json = await response.json();
        setPosts(json.data.children.map(it => it.data));
    } catch (e) {
        console.error(e);
    }
}, []);

并且我在我的控制台中收到此警告。但我认为清理对于异步调用是可选的。我不确定为什么会收到此警告。链接沙箱的例子。 https://codesandbox.io/s/24rj871r0p

当你使用像

这样的异步函数时
async () => {
    try {
        const response = await fetch(`https://www.reddit.com/r/${subreddit}.json`);
        const json = await response.json();
        setPosts(json.data.children.map(it => it.data));
    } catch (e) {
        console.error(e);
    }
}

它 return 是一个承诺,useEffect 不期望回调函数到 return Promise,而是期望没有任何 returned 或函数是returned.

作为警告的解决方法,您可以使用自调用异步函数。

useEffect(() => {
    (async function() {
        try {
            const response = await fetch(
                `https://www.reddit.com/r/${subreddit}.json`
            );
            const json = await response.json();
            setPosts(json.data.children.map(it => it.data));
        } catch (e) {
            console.error(e);
        }
    })();
}, []);

或者为了让它更简洁,您可以定义一个函数然后调用它

useEffect(() => {
    async function fetchData() {
        try {
            const response = await fetch(
                `https://www.reddit.com/r/${subreddit}.json`
            );
            const json = await response.json();
            setPosts(json.data.children.map(it => it.data));
        } catch (e) {
            console.error(e);
        }
    };
    fetchData();
}, []);

第二个解决方案将使其更易于阅读,并将帮助您编写代码以在触发新请求时取消以前的请求或将最新的请求响应保存在状态中

Working codesandbox

我建议看看Dan Abramov (one of the React core maintainers) answer here:

I think you're making it more complicated than it needs to be.

function Example() {
  const [data, dataSet] = useState<any>(null)

  useEffect(() => {
    async function fetchMyAPI() {
      let response = await fetch('api/data')
      response = await response.json()
      dataSet(response)
    }

    fetchMyAPI()
  }, [])

  return <div>{JSON.stringify(data)}</div>
}

Longer term we'll discourage this pattern because it encourages race conditions. Such as — anything could happen between your call starts and ends, and you could have gotten new props. Instead, we'll recommend Suspense for data fetching which will look more like

const response = MyAPIResource.read();

and no effects. But in the meantime you can move the async stuff to a separate function and call it.

您可以阅读有关 experimental suspense here 的更多信息。


如果你想在 eslint 之外使用函数。

 function OutsideUsageExample({ userId }) {
  const [data, dataSet] = useState<any>(null)

  const fetchMyAPI = useCallback(async () => {
    let response = await fetch('api/data/' + userId)
    response = await response.json()
    dataSet(response)
  }, [userId]) // if userId changes, useEffect will run again

  useEffect(() => {
    fetchMyAPI()
  }, [fetchMyAPI])

  return (
    <div>
      <div>data: {JSON.stringify(data)}</div>
      <div>
        <button onClick={fetchMyAPI}>manual fetch</button>
      </div>
    </div>
  )
}

如果您使用 useCallback,请查看其工作原理示例 useCallback. Sandbox

import React, { useState, useEffect, useCallback } from "react";

export default function App() {
  const [counter, setCounter] = useState(1);

  // if counter is changed, than fn will be updated with new counter value
  const fn = useCallback(() => {
    setCounter(counter + 1);
  }, [counter]);

  // if counter is changed, than fn will not be updated and counter will be always 1 inside fn
  /*const fnBad = useCallback(() => {
      setCounter(counter + 1);
    }, []);*/

  // if fn or counter is changed, than useEffect will rerun
  useEffect(() => {
    if (!(counter % 2)) return; // this will stop the loop if counter is not even

    fn();
  }, [fn, counter]);

  // this will be infinite loop because fn is always changing with new counter value
  /*useEffect(() => {
    fn();
  }, [fn]);*/

  return (
    <div>
      <div>Counter is {counter}</div>
      <button onClick={fn}>add +1 count</button>
    </div>
  );
}

在 React 提供更好的方法之前,您可以创建一个助手,useEffectAsync.js:

import { useEffect } from 'react';


export default function useEffectAsync(effect, inputs) {
    useEffect(() => {
        effect();
    }, inputs);
}

现在你可以传递一个异步函数了:

useEffectAsync(async () => {
    const items = await fetchSomeItems();
    console.log(items);
}, []);

更新

如果您选择这种方法,请注意这是一种错误的形式。当我知道它是安全的时候我会求助于它,但它总是糟糕的形式和随意的。

Suspense for Data Fetching,仍处于实验阶段,将解决部分情况。

在其他情况下,您可以将异步结果建模为事件,以便您可以根据组件生命周期添加或删除侦听器。

或者您可以将异步结果建模为 Observable,以便您可以根据组件生命周期订阅和取消订阅。

看完这个问题,感觉答案中没有提到实现useEffect的最佳方式。 假设您有一个网络呼叫,并且希望在得到响应后做某事。 为了简单起见,让我们将网络响应存储在状态变量中。 人们可能想使用 action/reducer 来通过网络响应更新商店。

const [data, setData] = useState(null);

/* This would be called on initial page load */
useEffect(()=>{
    fetch(`https://www.reddit.com/r/${subreddit}.json`)
    .then(data => {
        setData(data);
    })
    .catch(err => {
        /* perform error handling if desired */
    });
}, [])

/* This would be called when store/state data is updated */
useEffect(()=>{
    if (data) {
        setPosts(data.children.map(it => {
            /* do what you want */
        }));
    }
}, [data]);

参考 => https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects

尝试

const MyFunctionnalComponent: React.FC = props => {
  useEffect(() => {
    // Using an IIFE
    (async function anyNameFunction() {
      await loadContent();
    })();
  }, []);
  return <div></div>;
};

对于其他读者,错误可能来自于异步函数没有括号:

考虑异步函数 initData

  async function initData() {
  }

此代码将导致您的错误:

  useEffect(() => initData(), []);

但是这个,不会:

  useEffect(() => { initData(); }, []);

(注意 initData()

两边的括号

void operator可以用在这里
而不是:

React.useEffect(() => {
    async function fetchData() {
    }
    fetchData();
}, []);

React.useEffect(() => {
    (async function fetchData() {
    })()
}, []);

你可以这样写:

React.useEffect(() => {
    void async function fetchData() {
    }();
}, []);

它更干净、更漂亮了。


异步效果可能会导致内存泄漏,因此在组件卸载时执行清理很重要。在 fetch 的情况下,这可能看起来像这样:

function App() {
    const [ data, setData ] = React.useState([]);

    React.useEffect(() => {
        const abortController = new AbortController();
        void async function fetchData() {
            try {
                const url = 'https://jsonplaceholder.typicode.com/todos/1';
                const response = await fetch(url, { signal: abortController.signal });
                setData(await response.json());
            } catch (error) {
                console.log('error', error);
            }
        }();
        return () => {
            abortController.abort(); // cancel pending fetch request on component unmount
        };
    }, []);

    return <pre>{JSON.stringify(data, null, 2)}</pre>;
}

请试试这个

 useEffect(() => {
        (async () => {
          const products = await api.index()
          setFilteredProducts(products)
          setProducts(products)
        })()
      }, [])

要使用 React Hooks 从外部 API 获取,您应该调用一个从 useEffect 钩子内部的 API 获取的函数。

像这样:

async function fetchData() {
    const res = await fetch("https://swapi.co/api/planets/4/");
    res
      .json()
      .then(res => setPosts(res))
      .catch(err => setErrors(err));
  }

useEffect(() => {
    fetchData();
}, []);

我强烈建议你不要在 useEffect Hook 中定义你的查询,因为它会被重新渲染无限次。并且由于您无法使 useEffect 异步,因此您可以将其中的函数设为异步。

在上面显示的示例中,API 调用在另一个 分离的异步函数中 因此它确保调用是异步的并且只发生一次。此外,useEffect's 依赖数组([])是空的,这意味着它的行为就像 React Class 组件中的 componentDidMount 一样,它只会在组件安装时执行一次。

对于加载文本,您可以使用 React 的条件渲染 来验证您的帖子是否为空,如果是,则渲染加载文本,否则显示帖子。当您完成从 API 中获取数据并且帖子不为空时,else 将为真。

{posts === null ? <p> Loading... </p> 
: posts.map((post) => (
    <Link key={post._id} to={`/blog/${post.slug.current}`}>
      <img src={post.mainImage.asset.url} alt={post.mainImage.alt} />
      <h2>{post.title}</h2>
   </Link>
))}

我看到您已经在使用条件渲染,所以我建议您深入研究它,尤其是验证对象是否为空!

我建议您阅读以下文章,以防您需要有关使用 Hooks 使用 API 的更多信息。

https://betterprogramming.pub/how-to-fetch-data-from-an-api-with-react-hooks-9e7202b8afcd

https://reactjs.org/docs/conditional-rendering.html

使用自定义提供的 useAsyncEffect 挂钩 library, safely execution of async code and making requests inside effects become trivially since it makes your code auto-cancellable (this is just one thing from the feature list). Check out the Live Demo with JSON fetching

import React from "react";
import { useAsyncEffect } from "use-async-effect2";
import cpFetch from "cp-fetch";

/*
 Notice: the related network request will also be aborted
 Checkout your network console
 */

function TestComponent(props) {
  const [cancel, done, result, err] = useAsyncEffect(
    function* () {
      const response = yield cpFetch(props.url).timeout(props.timeout);
      return yield response.json();
    },
    { states: true, deps: [props.url] }
  );

  return (
    <div className="component">
      <div className="caption">useAsyncEffect demo:</div>
      <div>
        {done ? (err ? err.toString() : JSON.stringify(result)) : "loading..."}
      </div>
      <button className="btn btn-warning" onClick={cancel} disabled={done}>
        Cancel async effect
      </button>
    </div>
  );
}

export default TestComponent;

The same demo using axios

将其包装成 useCallback 并将其用作 useEffect 挂钩的依赖项。

const getPosts = useCallback(async () => {
    try {
        const response = await fetch(`https://www.reddit.com/r/${subreddit}.json`);
        const json = await response.json();
        setPosts(json.data.children.map(it => it.data));
    } catch (e) {
        console.error(e);
    }
}, []);

useEffect(async () => {
    getPosts();
}, [getPosts]);

您也可以使用 IIFE 格式来保持简短

function Example() {
    const [data, dataSet] = useState<any>(null)

    useEffect(() => {
        (async () => {
            let response = await fetch('api/data')
            response = await response.json()
            dataSet(response);
        })();
    }, [])

    return <div>{JSON.stringify(data)}</div>
}

请注意纯脚本语言如何使用 Aff monad

处理陈旧效果的问题

没有原稿

你必须使用 AbortController

function App() {
    const [ data, setData ] = React.useState([]);

    React.useEffect(() => {
        const abortController = new AbortController();
        void async function fetchData() {
            try {
                const url = 'https://jsonplaceholder.typicode.com/todos/1';
                const response = await fetch(url, { signal: abortController.signal });
                setData(await response.json());
            } catch (error) {
                console.log('error', error);
            }
        }();
        return () => {
            abortController.abort(); // cancel pending fetch request on component unmount
        };
    }, []);

    return <pre>{JSON.stringify(data, null, 2)}</pre>;
}

stale (from NoahZinsmeister/web3-react example)

function Balance() {
  const { account, library, chainId } = useWeb3React()

  const [balance, setBalance] = React.useState()
  React.useEffect((): any => {
    if (!!account && !!library) {      
      let stale = false
      
      library 
        .getBalance(account)
        .then((balance: any) => {
          if (!stale) {
            setBalance(balance)
          }
        })
        .catch(() => {
          if (!stale) {
            setBalance(null)
          }
        })

      return () => { // NOTE: will be called every time deps changes
        stale = true
        setBalance(undefined)
      }
    }
  }, [account, library, chainId]) // ensures refresh if referential identity of library doesn't change across chainIds

  ...

有原著

检查如何 useAff kills it's Aff in the cleanup function

Aff 实现为 state machine (without promises)

但这里与我们相关的是:

忽略警告,并使用带有 async functionuseEffect 挂钩,如下所示:

import { useEffect, useState } from "react";

function MyComponent({ objId }) {
  const [data, setData] = useState();

  useEffect(() => {
    if (objId === null || objId === undefined) {
      return;
    }

    async function retrieveObjectData() {
      const response = await fetch(`path/to/api/objects/${objId}/`);
      const jsonData = response.json();
      setData(jsonData);
    }
    retrieveObjectData();

  }, [objId]);

  if (objId === null || objId === undefined) {
    return (<span>Object ID needs to be set</span>);
  }

  if (data) {
    return (<span>Object ID is {objId}, data is {data}</span>);
  }

  return (<span>Loading...</span>);
}

其他答案已经有很多例子给出,解释的很清楚,所以我就从TypeScript类型定义的角度来解释。

useEffect hook TypeScript 签名:

function useEffect(effect: EffectCallback, deps?: DependencyList): void;

effect的类型:

// NOTE: callbacks are _only_ allowed to return either void, or a destructor.
type EffectCallback = () => (void | Destructor);

// Destructors are only allowed to return void.
type Destructor = () => void | { [UNDEFINED_VOID_ONLY]: never };

现在我们应该知道为什么 effect 不能是 async 函数了。

useEffect(async () => {
  //...
}, [])

异步函数将 return 具有隐式 undefined 值的 JS promise。这不是useEffect.

的期待

我知道已经晚了,但我遇到了同样的问题,我想分享一下我用这样的函数解决了它!

useEffect(() => {
(async () => { 
  try {
   const response = await fetch(`https://www.reddit.com/r/${subreddit}.json`);
   const json = await response.json();
    setPosts(json.data.children.map(it => it.data));
  } catch (e) {
console.error(e);
}
}) ()   
}, [])