React Native - [Unhandled promise rejection: Error: Signup Error]

我的梦境 提交于 2021-01-29 05:17:26

问题


I get this intentional error because I'm using the same email to register. It says I'm not handling the rejection; can someone explain why because I have a .catch() which should catch any errors that were thrown

Error code:

[Unhandled promise rejection: Error: Signup Error]
- node_modules\promise\setimmediate\core.js:37:14 in tryCallOne
- node_modules\promise\setimmediate\core.js:123:25 in setImmediate$argument_0
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:146:14 in _callTimer
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:194:17 in _callImmediatesPass
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:458:30 in callImmediates
* [native code]:null in callImmediates
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:407:6 in __callImmediates
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:143:6 in __guard$argument_0
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:384:10 in __guard
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:142:17 in __guard$argument_0
* [native code]:null in flushedQueue
* [native code]:null in callFunctionReturnFlushedQueue

from this fetch().then().catch() code:

 fetch(
      "https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=[ API KEY ]",
      {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, password, returnSecureToken: true }),
      }
    )
      .then((res) => {
        if (!res.ok) {
          throw new Error("Signup Error");
        } else {
          const resData = res.json();
          return resData;
        }
      })
      .then((resData) => {
        console.log({ resData });
        dispatch({ type: SIGNUP });
      })
      .catch((err) => {
        console.log({ errHere: err });
        throw err;
      });

The try{}catch(){} code that does work:

try {
      const res = await fetch(
        "https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=[ API KEY ]",
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ email, password, returnSecureToken: true }),
        }
      );

      if (!res.ok) {
        throw new Error("Signup Error");
      }

      const resData = await res.json();

      console.log({ resData });
    } catch (err) {
      throw err;
    }

I've redone this code with try catch and it works but this puzzles me, so I need to know why it doesn't work with the .then().catch() handlers

The React code is this:

const signupHandler = useCallback(async () => {
    console.log(formState.inputValues.email, formState.inputValues.password);
    dispatch(
      signup(formState.inputValues.email, formState.inputValues.password)
    )
      .then(() => {
        console.log("OK!");
      })
      .catch((err) => {
        console.log({ errOutside: err });
      });
  }, [dispatch]);

and as I said it works with the try catch method.


回答1:


I'm not 100% sure of this since i'm used to try catch, but it could be because you are not actually handling the promise rejection:

in your then

  .then((res) => {
            if (!res.ok) {
              throw new Error("Signup Error");
            } else {
              const resData = res.json();
              return resData;
            }
          }, (reject) => {
             // handle this
          })



回答2:


dispatch is a synchronous method in redux and in try catch you used async await which is asynchronous what you can do is adding a asynchronous dispatch middleware to your redux store

const asyncDispatchMiddleware = (store) => (next) => (action) => {
  let syncActivityFinished = false;
  let actionQueue = [];

  function flushQueue() {
    actionQueue.forEach((a) => store.dispatch(a)); // flush queue
    actionQueue = [];
  }

  function asyncDispatch(asyncAction) {
    actionQueue = actionQueue.concat([asyncAction]);

    if (syncActivityFinished) {
      flushQueue();
    }
  }

  const actionWithAsyncDispatch = Object.assign({}, action, { asyncDispatch });

  next(actionWithAsyncDispatch);
  syncActivityFinished = true;
  flushQueue();
};

now you can make in promise scheme the asyncDispatch method



来源:https://stackoverflow.com/questions/62106794/react-native-unhandled-promise-rejection-error-signup-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!