简体   繁体   English

如何修复以避免 React 中的 ESLint Effect 回调警告

[英]How to fix to avoid ESLint Effect callbacks warning in React

I want to use the async/await pattern in my useEffect React hook and I'm getting an ESLint warning that I don't understand.我想在我的useEffect React 钩子中使用 async/await 模式,但我收到了一个我不明白的 ESLint 警告。

Here is my code that causes the warning这是我的导致警告的代码

useEffect(async () => {
 const delay = () => new Promise((resolve) => setTimeout(resolve, 1000));
 async function getData() {
   await delay();
 }
 getData();
}, []);

and the warning:和警告:

ESLint: Effect callbacks are synchronous to prevent race conditions. Put the async function inside: (react-hooks/exhaustive-deps)

The answer from a similar question says to add useCallback , but as I have no dependencies, it does not seem to help.类似问题的答案说添加useCallback ,但由于我没有依赖项,它似乎没有帮助。

How to fix missing dependency warning when using useEffect React Hook 使用 useEffect React Hook 时如何修复缺少的依赖警告

Here is what that incorrect answer looks like:这是错误答案的样子:

    const delay = () => new Promise((resolve) => setTimeout(resolve, 1000));
    async function getData() {
      await delay();
    }
    getData();
  },[]), []);

You shouldn't make a usEffect asynchronous.您不应该使usEffect异步。 Instead add it to the outside of your useEffect .而是将其添加到您的useEffect之外。 Here is a Stackoverflow answer that gives one reason why.是一个 Stackoverflow 答案,它给出了一个原因。 Instead:反而:

const delay = () => new Promise((resolve) => setTimeout(resolve, 1000));
async function getData() {
    await delay();
}
useEffect(() => { // don't need async here
  getData();
}, []);
useEffect(async () => { // don't need async here
    const delay = () => new Promise((resolve) => setTimeout(resolve, 1000));
    async function getData() {
    await delay();
  }
 getData();
}, []);

The error is telling you not to use async in the call to useEffect() itself.该错误告诉您不要在对useEffect()本身的调用中使用async Look here, you have this exact anti-pattern: https://dev.to/danialdezfouli/what-s-wrong-with-the-async-function-in-useeffect-4jne看这里,你有这个确切的反模式: https://dev.to/danialdezfouli/what-s-wrong-with-the-async-function-in-useeffect-4jne

Also notice how the parentheses in that example are being used to scope the async function as an IIFE so it runs without being explicitly called.另请注意,该示例中的括号如何用于 scope async function 作为 IIFE,因此它无需显式调用即可运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM