React Native:Promise的then语句中setState不生效问题咨询
问题排查与解决方案
嘿,这个问题我之前刚碰到过,大概率是this的上下文指向不对搞的鬼!咱们一步步拆解:
最可能的原因:Promise回调里的this不是组件实例
在JavaScript里,普通函数作为Promise的.then回调时,它的this指向会默认绑定到全局对象(React Native里是global),而不是你的React组件实例。这就导致你在.then里调用this.setState时,根本找不到组件的setState方法,自然没法更新modalVisable状态来关闭Modal。
而你在.catch里能用,大概率是因为你在.catch里用了箭头函数——箭头函数不会绑定自己的this,会继承外层作用域的this(也就是你的组件实例),所以this.setState能正常生效。
快速解决方案
把.then里的回调改成箭头函数,或者手动绑定this:
方案1:用箭头函数(最推荐)
// 假设你的登录请求是这样的 loginApi(username, password) .then((response) => { // 箭头函数继承外层的this,也就是组件实例 this.setState({ modalVisable: false }); // 这里还可以处理登录成功后的逻辑,比如跳转到首页 }) .catch((error) => { this.setState({ modalVisable: false }); // 处理登录失败,比如提示错误信息 });
方案2:提前保存this的引用
如果习惯用普通函数,也可以在Promise前把组件的this存起来:
const that = this; // 保存组件的this引用 loginApi(username, password) .then(function(response) { that.setState({ modalVisable: false }); // 用that代替this }) .catch(function(error) { that.setState({ modalVisable: false }); });
方案3:用bind绑定this
给普通函数回调手动绑定组件的this:
loginApi(username, password) .then(function(response) { this.setState({ modalVisable: false }); }.bind(this)) // 绑定组件的this .catch(function(error) { this.setState({ modalVisable: false }); }.bind(this));
额外排查点
如果上面的方法没用,你可以加个console.log看看.then里的代码有没有执行:
.then((response) => { console.log("登录成功进入then了!", this); // 看看this是不是组件实例 this.setState({ modalVisable: false }); })
如果控制台没输出,说明你的Promise根本没进入resolve状态——比如登录请求成功了但后端没返回正确的响应,或者Promise内部没调用resolve(),这时候得检查你的Promise逻辑哦。
内容的提问来源于stack exchange,提问作者Charles Maddock
相关产品推荐
相关产品推荐

