Firebase认证代码中,.then()内调用函数抛出错误求解决
解决Firebase Auth Promise中的绑定错误
我来帮你搞定这个问题——你遇到的错误核心是在Promise的then/catch方法里传递函数的方式出了问题,咱们一步步拆解清楚:
错误原因分析
你代码里写的then(this.onAuthSuccess().bind(this))是典型的误区:
- 首先,
this.onAuthSuccess()会立即执行这个函数,此时函数内部的this还没有正确绑定到组件实例,而且这个函数本身没有返回值(默认返回undefined) - 接着你尝试对
undefined调用.bind(this),自然就会抛出undefined is not an object (evaluating '_this.onAuthSuccess().bind()')的错误
简单总结:Promise的then/catch需要接收函数引用,而不是函数执行后的结果。
修正方案
这里有几种可靠的修正方式,你可以任选其一:
方式1:提前用bind绑定函数(推荐)
直接传递绑定好this的函数引用给then/catch:
onButtonPress = () => { const {email, password} = this.state this.setState({error: '', loading: true}); firebase.auth().signInWithEmailAndPassword(email, password) .then(this.onAuthSuccess.bind(this)) .catch(() => { firebase.auth().createUserWithEmailAndPassword(email, password) .then(this.onAuthSuccess.bind(this)) .catch(this.onAuthFailed.bind(this)) }) } onAuthSuccess() { this.setState({ email: '', password: '', error: '', loading: false }) } onAuthFailed() { this.setState({ error: "Authentication Failed", loading: false }) }
方式2:用箭头函数包裹(更直观)
箭头函数会自动继承当前上下文的this,不需要手动绑定:
onButtonPress = () => { const {email, password} = this.state this.setState({error: '', loading: true}); firebase.auth().signInWithEmailAndPassword(email, password) .then(() => this.onAuthSuccess()) .catch(() => { firebase.auth().createUserWithEmailAndPassword(email, password) .then(() => this.onAuthSuccess()) .catch(() => this.onAuthFailed()) }) } onAuthSuccess() { this.setState({ email: '', password: '', error: '', loading: false }) } onAuthFailed() { this.setState({ error: "Authentication Failed", loading: false }) }
方式3:把回调函数定义为箭头函数(一劳永逸)
如果把onAuthSuccess和onAuthFailed直接定义为箭头函数,它们的this会自动绑定到组件实例,后续调用时无需额外处理:
onButtonPress = () => { const {email, password} = this.state this.setState({error: '', loading: true}); firebase.auth().signInWithEmailAndPassword(email, password) .then(this.onAuthSuccess) .catch(() => { firebase.auth().createUserWithEmailAndPassword(email, password) .then(this.onAuthSuccess) .catch(this.onAuthFailed) }) } onAuthSuccess = () => { this.setState({ email: '', password: '', error: '', loading: false }) } onAuthFailed = () => { this.setState({ error: "Authentication Failed", loading: false }) }
内容的提问来源于stack exchange,提问作者Zainul Abideen
相关产品推荐
相关产品推荐

