简体   繁体   English

异步 function 作为 prop 传递给 React 组件,导致 @typescript-eslint/no-misused-promises 错误

[英]Async function passed as prop into React component causing @typescript-eslint/no-misused-promises error

I have the following asynchronous submitNewPatient function which is throwing @typescript-eslint/no-misused-promises error message from elint.我有以下异步submitNewPatient function,它从 elint 中抛出@typescript-eslint/no-misused-promises错误消息。 Is it possible to adjust the function such that it removes this error?是否可以调整 function 以消除此错误?

const submitNewPatient = async (values: PatientFormValues) => {
    try {
      const { data: newPatient } = await axios.post<Patient>(
        `${apiBaseUrl}/patients`,
        values
      );
      dispatch({ type: "ADD_PATIENT", payload: newPatient });
      closeModal();
    } catch (e: unknown) {
      if (axios.isAxiosError(e)) {
        console.error(e?.response?.data || "Unrecognized axios error");
        setError(
          String(e?.response?.data?.error) || "Unrecognized axios error"
        );
      } else {
        console.error("Unknown error", e);
        setError("Unknown error");
      }
    }
  };

Component used to pass function as a prop:用于传递 function 作为 prop 的组件:

<AddPatientModal
        modalOpen={modalOpen}
        onSubmit={submitNewPatient}
        error={error}
        onClose={closeModal}
      />

I have also tried the following which removes the eslint error message based.我还尝试了以下删除基于 eslint 错误消息的方法。 However, seems like I am not entering the async code block (perhaps not triggering the async() function):但是,似乎我没有进入异步代码块(可能没有触发 async() 函数):

  const submitNewPatient = (values: PatientFormValues) => {
    async () => {
      try {
        const { data: newPatient } = await axios.post<Patient>(
          `${apiBaseUrl}/patients`,
          values
        );
        dispatch({ type: "ADD_PATIENT", payload: newPatient });
        closeModal();
      } catch (e: unknown) {
        if (axios.isAxiosError(e)) {
          console.error(e?.response?.data || "Unrecognized axios error");
          setError(
            String(e?.response?.data?.error) || "Unrecognized axios error"
          );
        } else {
          console.error("Unknown error", e);
          setError("Unknown error");
        }
      }
    };
  };

I think the problem is with the async code block syntax.我认为问题出在async代码块语法上。 You need it to make it an IIFE (Immediately-invoked Function Expression for it to be executed immediately.您需要它来使它成为一个IIFE (立即调用 Function 表达式,以便立即执行。

(async () => {
    await someAsyncFunction();
})();

Your submitNewPatient becomes -您的submitNewPatient变为 -

const submitNewPatient = (values: PatientFormValues) => {
    (async () => {
      try {
        const { data: newPatient } = await axios.post<Patient>(
          `${apiBaseUrl}/patients`,
          values
        );
        dispatch({ type: "ADD_PATIENT", payload: newPatient });
        closeModal();
      } catch (e: unknown) {
        if (axios.isAxiosError(e)) {
          console.error(e?.response?.data || "Unrecognized axios error");
          setError(
            String(e?.response?.data?.error) || "Unrecognized axios error"
          );
        } else {
          console.error("Unknown error", e);
          setError("Unknown error");
        }
      }
    })();
  };

The problem is not in your code but in the ESLint rule or the ESLint config.问题不在您的代码中,而在 ESLint 规则或 ESLint 配置中。 React 17 and later can handle async functions as event handlers. React 17 及更高版本可以将异步函数作为事件处理程序来处理。

The IIFE gets rid of the ESLint error but the error should not appear in the first place. IIFE 摆脱了 ESLint 错误,但错误不应该首先出现。 Unless you are using React 16 or earlier.除非你使用的是 React 16 或更早版本。

There was a lengthy discussion about the rule on Github .关于Github的规则进行了长时间的讨论。

The proposed solution is to remove the check for attributes or arguments:建议的解决方案是删除对属性或 arguments 的检查:

{
  "@typescript-eslint/no-misused-promises": [
    "error",
    {"checksVoidReturn": {"attributes": false}}
  ]
}

https://typescript-eslint.io/rules/no-misused-promises/ https://typescript-eslint.io/rules/no-misused-promises/

暂无
暂无

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

相关问题 作为 prop 传入的 function 的 React 组件抛出 TypeScript 错误 - React component throwing TypeScript error for function passed in as prop 打字稿反应组件中的反应/道具类型eslint错误 - react/prop-types eslint error in typescript react component 如何键入异步 function 作为道具传递给 React 组件 - How to type async function passed as prop to React component 反应:缺少函数的返回类型。 eslint(@typescript-eslint/explicit-function-return-type) - React: Missing return type on function. eslint(@typescript-eslint/explicit-function-return-type) TypeScript 的 Eslint 反应/道具类型错误 - Eslint react/prop-types error with TypeScript 创建反应应用程序 - 没有打字稿,得到错误:无法加载解析器&#39;@typescript-eslint/parser&#39; - create react app - without typescript , got Error: Failed to load parser '@typescript-eslint/parser' ESLint - function 反应组件上缺少返回类型 - Typescript 错误解释 - ESLint - missing return type on function react component - Typescript error explanation IONIC / REACT 第 9:5 行:期望一个赋值或函数调用,而是看到一个表达式 @typescript-eslint/no-unused-expressions - IONIC / REACT Line 9:5: Expected an assignment or function call and instead saw an expression @typescript-eslint/no-unused-expressions 期望分配或 function 调用,而是看到一个表达式 @typescript-eslint/no-unused-expressions (React) - Expected an assignment or function call and instead saw an expression @typescript-eslint/no-unused-expressions (React) 函数没有作为道具传递给 React 中的子组件 - Function not being passed as prop to child component in React
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM