Typescript 对象内 this 值为 undefined

问题描述:打印this值为undefined

import { Injectable, NestMiddleware } from '@nestjs/common';
import { CacheUtil } from 'src/utils/cache.util';

@Injectable()
export class GlobalMiddleware implements NestMiddleware {
    constructor(
        private readonly cacheUtil: CacheUtil
    ) { }
    
    async use(req: any, res: Response, next: () => void) {
        console.log(this);  // undefined
        console.log(this.cacheUtil);  // Cannot read properties of undefined (reading 'cacheUtil')

        next();
    }
}

nest 中间件中遇到的问题,为什么this的值为undefined

该回答通过自己思路及引用到GPTᴼᴾᴱᴺᴬᴵ搜索,得到内容具体如下:
在 TypeScript 中,如果你直接在构造函数中使用类成员变量,或者在类方法中使用 this 关键字时,需要注意作用域的问题,因为在 JavaScript 中,函数在被调用的时候,会根据调用方式来确定 this 的值。而在 TypeScript 中,如果你没有明确指定 this 的类型,编译器会默认将它视为 any 类型,这就可能导致 this 的值为 undefined

在你的代码中,use 方法是一个异步方法,所以它的执行上下文和构造函数的执行上下文不同。在 use 方法中,this 的值不再是当前对象的实例,而是当前方法被调用时的执行上下文。所以,当你尝试在 use 方法中访问 this.cacheUtil 时,会抛出 Cannot read properties of undefined 错误。

为了解决这个问题,你需要显式地指定 this 的类型。你可以将 use 方法的签名修改为以下形式:

async use(req: any, res: Response, next: () => void): Promise<void> {
  // ...
}

这样,你就为 use 方法指定了返回类型为 void,而 Promise<void> 则是 this 的类型。这样就可以正常访问 this.cacheUtil 了。


如果以上回答对您有所帮助,点击一下采纳该答案~谢谢

我记得箭头函数中应该是没有this指向的、下面是修改后的代码

@Injectable()
export class GlobalMiddleware implements NestMiddleware {
    constructor(private readonly cacheUtil: CacheUtil) {
        this.use = this.use.bind(this);
    }
   var _this = this;
    async use(req: any, res: Response, next: () => void) {
        console.log(_this );  // GlobalMiddleware { cacheUtil: CacheUtil {} }
        console.log(this.cacheUtil);  // CacheUtil {}
 
        next();
    }
}

或者把next改成正常的function

有空的话你可以试一下