Catch块在注册流程的Try块之前运行

huangapple go评论95阅读模式
英文:

Catch block running before Try block in signup process

问题

I'm experiencing an issue where the catch block in my signup process is running before the try block. When I attempt to sign up, the catch block displays the error message before the success message is shown. This behavior is unexpected, as I would expect the try block to execute first.

Here is the relevant code snippet:

const onSignup = async (values: any) => {
    try {
        setLoading(true);
        const response = await axios.post(`/api/users/signup`, values);
        const responseData = response.data;
        if (!responseData.error) {
            toast.success("Signup success", successState);
            router.push("/login");
        } else {
            if (responseData.error === "User already exists") {
                toast.error("User already exists", errorState);
            }
        }
    } catch (error: any) {
        toast.error(
            "An error occurred during sign in. Please try again later.",
            errorState
        );
    } finally {
        setLoading(false);
    }
};
英文:

I'm experiencing an issue where the catch block in my signup process is running before the try block. When I attempt to sign up, the catch block displays the error message before the success message is shown. This behavior is unexpected, as I would expect the try block to execute first.

Here is the relevant code snippet:

const onSignup = async (values: any) => {
        try {
          setLoading(true);
          const response = await axios.post(`/api/users/signup`, values);
          const responseData = response.data;
          if (!responseData.error) {
            toast.success("Signup success", successState);
            router.push("/login");
          } else {
            if (responseData.error === "User already exists") {
              toast.error("User already exists", errorState);
            }
          }
        } catch (error: any) {
          toast.error(
            "An error occurred during sign in. Please try again later.",
            errorState
          );
        } finally {
          setLoading(false);
        }
      };

答案1

得分: 1

在开发模式下,这可能是由于多次渲染而发生的 - 请查看此帖子 - https://stackoverflow.com/q/71847778/9640177

所以,实际上,您的捕获块不会被调用两次。您看到的错误来自前一个渲染。

英文:

In dev mode, this may be happening due to multiple renders - Check out this thread - https://stackoverflow.com/q/71847778/9640177

So, actually, your catch block is not called twice. The error you see is from the previous render.

huangapple
  • 本文由 发表于 2023年7月6日 19:57:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76628587.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定