React实现谷歌注册功能时触发未挂载组件状态更新警告如何解决
警告触发原因
这个警告的根本原因是:你调用auth.createUserWithEmailAndPassword注册成功后,Firebase的授权状态会立即更新,你项目全局的登录状态监听逻辑检测到用户已登录,会直接跳转到登录后的页面,此时SignUp组件已经被卸载。但后续的await createUserProfileDocument(user, { displayName })异步操作还在执行,等该操作完成后调用this.setState清空表单时,目标组件已经不存在,就触发了该内存泄漏警告。
修复方案
你可以通过给组件加挂载状态标记的方式快速修复,修改SignUp组件代码如下:
class SignUp extends React.Component { constructor() { super(); this.state = { displayName: '', email: '', password: '', confirmPassword: '' }; // 新增组件挂载状态标记 this._isMounted = false; } componentDidMount() { this._isMounted = true; } componentWillUnmount() { this._isMounted = false; } handleSubmit = async event => { event.preventDefault(); const { displayName, email, password, confirmPassword } = this.state; if (password !== confirmPassword) { alert("passwords don't match"); return; } try { const { user } = await auth.createUserWithEmailAndPassword( email, password ); await createUserProfileDocument(user, { displayName }); // 调用setState前先判断组件是否还挂载 if (this._isMounted) { this.setState({ displayName: '', email: '', password: '', confirmPassword: '' }); } } catch (error) { console.error(error); } }; // 其余原有代码保持不变 }
如果你的业务逻辑里注册成功后不需要保留SignUp组件,也可以直接去掉清空表单的setState代码,也能解决这个问题。
内容的提问来源于stack exchange,提问作者Harsh Vardhan
相关产品推荐
相关产品推荐

