React登录页面报错:Undefined is not a function(this.setState调用问题)
解决React中login函数里
this.setState的「Undefined is not a function」错误 我来帮你搞定这个问题!你遇到的报错核心原因是回调函数里的this指向不对,导致无法调用组件的setState方法。
为什么会出问题?
你在firebase.auth().signInWithEmailAndPassword的then和catch里用了普通的function(user)和function(error)回调——这种普通函数会重新绑定this的指向,不再指向你的React组件实例,所以this.setState就变成了「undefined调用函数」,自然抛出错误。
三种可行的解决方案
方案一:改用箭头函数(最推荐)
箭头函数不会绑定自己的this,它会继承外层作用域的this(也就是你的组件实例),写法简洁又靠谱:
login = (email, password, navigate) => { this.setState({ loginButtonPressed: true }); firebase.auth().signInWithEmailAndPassword(email, password) .then((user) => { navigate('Profile'); }) .catch((error) => { this.setState({ loginButtonPressed: false }); Alert.alert(error.toString()); }); };
方案二:提前保存组件的this
在函数开头把组件的this赋值给一个变量(比如that),之后在回调里用这个变量代替this:
login = (email, password, navigate) => { const that = this; // 先把组件的this存起来 that.setState({ loginButtonPressed: true }); firebase.auth().signInWithEmailAndPassword(email, password) .then(function(user) { navigate('Profile'); }) .catch(function(error) { that.setState({ loginButtonPressed: false }); Alert.alert(error.toString()); }); };
方案三:用bind绑定this
给回调函数手动绑定组件的this,不过这种写法相对繁琐一些:
login = (email, password, navigate) => { this.setState({ loginButtonPressed: true }); firebase.auth().signInWithEmailAndPassword(email, password) .then(function(user) { navigate('Profile'); }) .catch(function(error) { this.setState({ loginButtonPressed: false }); Alert.alert(error.toString()); }.bind(this)); // 绑定组件的this到回调函数 };
另外要夸一句:你用箭头函数定义login方法的做法是对的,这保证了login函数本身的this指向组件实例,不然第一步的this.setState也会出问题哦~
内容的提问来源于stack exchange,提问作者Jean
相关产品推荐
相关产品推荐

