Firebase重新认证时未处理Promise拒绝问题求助
问题分析与解决方案
你遇到的问题核心是Promise链断裂,导致updateEmail的错误无法被后续catch捕获,同时setSuccess会被提前执行。
具体原因:
- 第一个
then块中调用了updateEmail(user, newEmail),但没有返回这个Promise。这会导致当前Promise链不会等待updateEmail完成,直接进入下一个then执行setSuccess。 updateEmail本身是异步Promise操作,当它因无效邮箱抛出错误时,因为没有被任何catch绑定,就会触发“潜在未处理Promise拒绝”错误。
修正方案
只需要在第一个then里返回updateEmail的Promise,让它加入到Promise链中:
const reAuthenticate = (currentPassword) => { const credential = EmailAuthProvider.credential( auth.currentUser.email, currentPassword ); return reauthenticateWithCredential(auth.currentUser, credential); }; const onEmailUpdate = (currentPassword, newEmail) => { reAuthenticate(currentPassword) .then(() => { const user = auth.currentUser; // 返回updateEmail的Promise,让它进入Promise链 return updateEmail(user, newEmail); }) .then(() => { setSuccess( "Email Updated! However this might take some time to take effect." ); }) .catch((e) => { console.log(e); setError(formatErrorMsg(e)) }); };
如果觉得Promise链式写法不够直观,也可以改用async/await,逻辑会更清晰:
const reAuthenticate = (currentPassword) => { const credential = EmailAuthProvider.credential( auth.currentUser.email, currentPassword ); return reauthenticateWithCredential(auth.currentUser, credential); }; const onEmailUpdate = async (currentPassword, newEmail) => { try { await reAuthenticate(currentPassword); const user = auth.currentUser; await updateEmail(user, newEmail); setSuccess("Email Updated! However this might take some time to take effect."); } catch (e) { console.log(e); setError(formatErrorMsg(e)); } };
修改后,Promise链会等待updateEmail执行完成:一旦它抛出错误,会直接进入catch块处理,不会触发未处理Promise拒绝;只有updateEmail成功时,才会执行setSuccess。
内容的提问来源于stack exchange,提问作者MattCouthon
相关产品推荐
相关产品推荐

