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

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

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:

  1. const onSignup = async (values: any) => {
  2. try {
  3. setLoading(true);
  4. const response = await axios.post(`/api/users/signup`, values);
  5. const responseData = response.data;
  6. if (!responseData.error) {
  7. toast.success("Signup success", successState);
  8. router.push("/login");
  9. } else {
  10. if (responseData.error === "User already exists") {
  11. toast.error("User already exists", errorState);
  12. }
  13. }
  14. } catch (error: any) {
  15. toast.error(
  16. "An error occurred during sign in. Please try again later.",
  17. errorState
  18. );
  19. } finally {
  20. setLoading(false);
  21. }
  22. };
英文:

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:

  1. const onSignup = async (values: any) => {
  2. try {
  3. setLoading(true);
  4. const response = await axios.post(`/api/users/signup`, values);
  5. const responseData = response.data;
  6. if (!responseData.error) {
  7. toast.success("Signup success", successState);
  8. router.push("/login");
  9. } else {
  10. if (responseData.error === "User already exists") {
  11. toast.error("User already exists", errorState);
  12. }
  13. }
  14. } catch (error: any) {
  15. toast.error(
  16. "An error occurred during sign in. Please try again later.",
  17. errorState
  18. );
  19. } finally {
  20. setLoading(false);
  21. }
  22. };

答案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:

确定