request.post回调中调用this.setState报TypeError,求解决方案
解决TypeError: this.setState is not a function问题
嘿,这个问题我太熟悉了!你遇到的TypeError: this.setState is not a function,核心原因是回调函数里的this指向已经不是你的组件实例了——普通的function回调会创建自己的作用域,导致this丢失了原本的组件上下文。
下面给你三种常用的解决办法,选哪种都能搞定:
方法1:使用箭头函数作为回调(推荐)
箭头函数不会绑定自己的this,它会继承外层作用域的this,也就是你的组件实例。修改后的代码如下:
recalcRequest(data){ let meth = data let brandCode = meth.brandCode let paymentAmount = this.props.location.query.anfrage.umsatz+"00" let merchantReference = this.props.location.query.cardid let jsonData = { brandCode : brandCode, paymentAmount : paymentAmount, merchantReference:merchantReference }; request.post({ headers: {'content-type' : 'application/x-www-form-urlencoded'}, url: 'http://localhost:8888/Backend/recalcSig.php', body: "data=" + JSON.stringify(jsonData) }, (err, response, body) => { // 这里改成箭头函数 if (err) throw err; body = JSON.parse(body) this.setState({ merchantSig: body.merchantSig, sessionValidity: body.request.sessionValidity, requestPaymentMethods: false, showCardDetails:true }) console.log('response: ', response); }) }
方法2:提前保存组件的this
在发起请求前,把组件的this赋值给一个变量(比如that或者self),然后在回调里用这个变量来调用setState:
recalcRequest(data){ let meth = data let brandCode = meth.brandCode let paymentAmount = this.props.location.query.anfrage.umsatz+"00" let merchantReference = this.props.location.query.cardid let jsonData = { brandCode : brandCode, paymentAmount : paymentAmount, merchantReference:merchantReference }; const that = this; // 保存组件的this引用 request.post({ headers: {'content-type' : 'application/x-www-form-urlencoded'}, url: 'http://localhost:8888/Backend/recalcSig.php', body: "data=" + JSON.stringify(jsonData) }, function(err, response, body){ if (err) throw err; body = JSON.parse(body) that.setState({ // 用that代替this merchantSig: body.merchantSig, sessionValidity: body.request.sessionValidity, requestPaymentMethods: false, showCardDetails:true }) console.log('response: ', response); }) }
方法3:用.bind(this)绑定回调的this
直接给回调函数绑定组件的this,确保它的作用域正确:
recalcRequest(data){ let meth = data let brandCode = meth.brandCode let paymentAmount = this.props.location.query.anfrage.umsatz+"00" let merchantReference = this.props.location.query.cardid let jsonData = { brandCode : brandCode, paymentAmount : paymentAmount, merchantReference:merchantReference }; request.post({ headers: {'content-type' : 'application/x-www-form-urlencoded'}, url: 'http://localhost:8888/Backend/recalcSig.php', body: "data=" + JSON.stringify(jsonData) }, function(err, response, body){ if (err) throw err; body = JSON.parse(body) this.setState({ merchantSig: body.merchantSig, sessionValidity: body.request.sessionValidity, requestPaymentMethods: false, showCardDetails:true }) console.log('response: ', response); }.bind(this)) // 绑定组件的this到回调函数 }
个人更推荐第一种箭头函数的写法,代码更简洁,也是现在React开发里的主流做法~
内容的提问来源于stack exchange,提问作者HarryTgerman
相关产品推荐
相关产品推荐

