我收到此故意错误,因为我使用同一封电子邮件进行注册。它说我没有处理拒绝;有人可以解释为什么原因,因为我有一个.catch()可以捕获引发的任何错误
错误代码:
[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
来自此fetch().then().catch()
代码:
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;
});
有效的try{}catch(){}
代码:
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;
}
我已经用try catch
重做了此代码,它可以工作,但这使我感到困惑,所以我需要知道为什么它在.then().catch()
处理程序中不起作用
React代码是这样:
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]);
并且正如我所说的,它与try catch
方法一起使用。
由于我习惯于尝试捕获,所以我对此不是100%的确定,但这可能是因为您实际上并未处理承诺拒绝:
dispatch是redux中的同步方法,在try catch
中使用了异步的async await
您可以做的是向您的redux存储中添加一个异步调度中间件