TypeScript传递函数执行时出现TypeError: Cannot set property报错求助
解决TypeScript中传递函数时的TypeError: Cannot set property问题
嘿,我一眼就看出你大概率踩了JavaScript/TypeScript里最常见的坑之一——this上下文丢失!当你把类的方法当作参数传递给另一个函数时,函数的this指向会脱离原本的类实例,导致你没法设置firstName、userName这些类属性,自然就抛出了TypeError: Cannot set property的错误。
结合你给出的代码片段来看,你在组件的constructor里调用了auth.handleAuthentication(),之后调用this.fetchProfile(),我猜测fetchProfile方法里肯定有类似这样的操作:把类里的某个处理函数直接传给了其他服务(比如placeService的某个方法),比如:
fetchProfile() { // 直接传方法,导致this指向丢失 this.placeService.getProfileData(this.handleProfileResult); } handleProfileResult(data) { // 这里的this已经不是NavigationComponent的实例了! this.userName = data.userName; this.dpUrl = data.dpUrl; }
别担心,有几种简单的办法能解决这个问题:
方案1:用箭头函数绑定上下文
箭头函数会自动捕获当前作用域的this,所以传递函数的时候用箭头函数包裹一下就行:fetchProfile() { this.placeService.getProfileData((data) => this.handleProfileResult(data)); }或者干脆把你的处理函数直接定义成箭头函数,这样它的
this会永远指向类实例:// 直接用箭头函数定义类方法 handleProfileResult = (data) => { this.userName = data.userName; this.dpUrl = data.dpUrl; }方案2:用bind()显式绑定this
如果你更习惯用普通函数,也可以在传递的时候用bind()把this强制绑定到类实例上:fetchProfile() { this.placeService.getProfileData(this.handleProfileResult.bind(this)); }
另外提一句,你在constructor里调用fetchProfile()之前就打印了this.firstName和this.userName,这时候这些属性可能还没被赋值,会显示undefined,但这不是导致你报错的原因——核心还是this的指向问题哦。
内容的提问来源于stack exchange,提问作者Raj Bhatia
相关产品推荐
相关产品推荐

