异步函数以prop的形式传递到React组件中,导致 @typescript-eslint/no-misused-promises错误

发布于 2025-01-27 01:04:33 字数 1751 浏览 4 评论 0原文

我有以下异步 submitnewpatient 函数,它正在抛出@typecript-eslint/no-misused-promises 错误消息。是否可以调整功能以消除此错误?

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");
      }
    }
  };

组件用于将函数作为道具传递:

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

我还尝试了以下操作,以删除基于ESLINT错误消息。但是,似乎我没有输入异步代码块(也许不是触发异步()函数):

  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 have the following asynchronous submitNewPatient function which is throwing @typescript-eslint/no-misused-promises error message from elint. Is it possible to adjust the function such that it removes this error?

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:

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

I have also tried the following which removes the eslint error message based. However, seems like I am not entering the async code block (perhaps not triggering the async() function):

  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");
        }
      }
    };
  };

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

笑着哭最痛 2025-02-03 01:04:33

问题不在您的代码中,而是在ESLINT规则或ESLINT配置中。 React 17及以后可以作为事件处理程序处理异步功能。

IIFE摆脱了ESLINT错误,但错误首先不应出现。除非您使用16或更早的React。

关于 github )的规则进行了漫长的讨论。

提出的解决方案是要删除属性或参数的检查:

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

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

The problem is not in your code but in the ESLint rule or the ESLint config. React 17 and later can handle async functions as event handlers.

The IIFE gets rid of the ESLint error but the error should not appear in the first place. Unless you are using React 16 or earlier.

There was a lengthy discussion about the rule on Github.

The proposed solution is to remove the check for attributes or arguments:

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

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

我乃一代侩神 2025-02-03 01:04:33

我认为问题是async代码块语法。 (立即执行的函数表达式。

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

您需要它使其成为 iife

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. You need it to make it an IIFE (Immediately-invoked Function Expression for it to be executed immediately.

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

Your submitNewPatient becomes -

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");
        }
      }
    })();
  };
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文