React注册场景下async/await+try/catch搭配.then()执行逻辑不符合预期
问题成因
- 按钮点击事件中,
then()方法里直接执行了handleRedirect(),而不是传入函数引用。代码执行到这里时会立刻调用跳转逻辑,不会等待注册异步请求返回结果。 registerWithEmailAndPassword函数内部通过catch吞掉了所有错误,即使注册失败,函数返回的Promise状态仍然是成功(fulfilled),后续的then回调一定会被触发。
修复方案
步骤1:修改注册函数,错误场景向外抛出异常
在registerWithEmailAndPassword的catch块最后新增错误抛出逻辑,避免吞掉错误,让外部可以感知到注册失败的状态:
const registerWithEmailAndPassword = async (name, email, password) => { try { console.log(name, email, password) const res = await createUserWithEmailAndPassword(auth, email, password); const user = res.user; await setDoc(doc(db, "users", email), { email: email, nombre: name, pass: password }); alert("注册成功") } catch (err) { console.error(err); alert(err.message); // 新增:抛出错误让外部Promise链感知到失败状态 throw err } };
步骤2:修改按钮点击回调,仅在注册成功后执行跳转
将then(handleRedirect())改为then(handleRedirect),传入函数引用,等待注册成功后再触发跳转逻辑:
<button id="submit" className="btn btn-outline-accesible col-3 m-2 mt-3" onClick={() => { registerWithEmailAndPassword(this.state.userName, this.state.email, this.state.password) .then(handleRedirect) // 不要加括号,避免立即执行 }}>提交</button>
小提示:
setState是异步执行的,你在handleRedirect里打印this.state大概率会拿到修改前的redirect值,这是正常现象,不影响跳转逻辑运行。
内容的提问来源于stack exchange,提问作者Pedro Montesinos Navarro
相关产品推荐
相关产品推荐

