TypeScript中bind(this)使用问题:React类组件报错修复方案
修复TypeScript中'this'隐式'any'的报错
下面是几种可行的修复方案:
方案1:使用箭头函数替代普通函数+bind
箭头函数会自动捕获外层上下文的this,不需要手动bind,TypeScript能正确推断this的类型为你的App组件实例,写法最简洁:
socket.onopen = () => { console.log("ws opened!!."); this.setState({ a: true, b: false, }) };
方案2:给普通函数添加this类型注解
明确指定函数内的this类型为你的组件类(这里是App),TypeScript就会识别this的具体类型,不再报隐式any的错误:
socket.onopen = (function(this: App) { console.log("ws opened!!."); this.setState({ a: true, b: false, }) }).bind(this);
方案3:提前缓存this到变量
把外层的this赋值给一个变量(比如self),在回调里直接使用这个变量,绕开this的绑定问题:
const self = this; socket.onopen = function() { console.log("ws opened!!."); self.setState({ a: true, b: false, }) };
其中方案1是React组件中处理回调的常用推荐写法,代码更简洁易读。
内容的提问来源于stack exchange,提问作者wts
相关产品推荐
相关产品推荐

