将TypeORM仓库函数存入变量后调用失败问题咨询
问题原因分析:TypeORM仓库方法引用调用报错"Cannot read properties of undefined (reading 'manager')"
核心问题是函数的
this指向丢失- 直接调用
this.sampleRepository.findOne()时,findOne方法内部的this会自动绑定到sampleRepository实例上,所以能正常访问实例的manager属性。 - 当你把
this.sampleRepository.findOne赋值给变量ref后,这个函数引用脱离了原实例的上下文。调用ref()时,findOne内部的this不再指向sampleRepository,在严格模式下会变成undefined,自然就找不到manager属性了。
- 直接调用
快速解决办法:
- 用
bind手动绑定上下文:const ref = this.sampleRepository.findOne.bind(this.sampleRepository); - 或者用箭头函数包裹(箭头函数会继承外层的
this):const ref = (...args) => this.sampleRepository.findOne(...args);
- 用
内容的提问来源于stack exchange,提问作者Kugesh Rajasekaran
相关产品推荐
相关产品推荐

