使用Postman请求时触发TypeError: itemService未定义错误
错误信息
TypeError: Cannot read properties of undefined (reading 'itemService')
at /home/monts/projects/MarysPizzaTS/src/controllers/Item.ts:11:34
at Generator.next ()
at /home/monts/projects/MarysPizzaTS/src/controllers/Item.ts:8:71
at new Promise ()
at __awaiter (/home/monts/projects/MarysPizzaTS/src/controllers/Item.ts:4:12)
at getAll (/home/monts/projects/MarysPizzaTS/src/controllers/Item.ts:21:16)
at Layer.handle [as handle_request] (/home/monts/projects/MarysPizzaTS/node_modules/express/lib/router/layer.js:95:5)
at next (/home/monts/projects/MarysPizzaTS/node_modules/express/lib/router/route.js:144:13)
at Route.dispatch (/home/monts/projects/MarysPizzaTS/node_modules/express/lib/router/route.js:114:3)
at Layer.handle [as handle_request] (/home/monts/projects/MarysPizzaTS/node_modules/express/lib/router/layer.js:95:5)
原ItemController代码
//ItemController import { Request, Response } from 'express'; import ItemService from '../services/Item'; class ItemController { private itemService: ItemService; constructor(itemService: ItemService) { this.itemService = new ItemService(); } async getAll(req: Request, res: Response) { const items = await this.itemService.getAll(); res.status(200).json(items); } } export default ItemController;
问题原因
- this上下文丢失:Express调用
getAll作为路由处理函数时,不会自动绑定类实例的this,导致this指向undefined,无法读取itemService属性。 - 依赖注入无效:构造函数接收了
itemService参数却未使用,反而重新实例化ItemService,违背了依赖注入的设计初衷。
修复方案
方案一:手动绑定this到实例
在构造函数中绑定getAll方法的this,同时修正依赖注入逻辑:
//ItemController import { Request, Response } from 'express'; import ItemService from '../services/Item'; class ItemController { private itemService: ItemService; constructor(itemService: ItemService) { // 使用传入的依赖实例,而非重新创建 this.itemService = itemService; // 绑定this到当前实例 this.getAll = this.getAll.bind(this); } async getAll(req: Request, res: Response) { const items = await this.itemService.getAll(); res.status(200).json(items); } } export default ItemController;
方案二:使用箭头函数定义方法
箭头函数会自动捕获外层作用域的this,无需手动绑定:
//ItemController import { Request, Response } from 'express'; import ItemService from '../services/Item'; class ItemController { private itemService: ItemService; constructor(itemService: ItemService) { this.itemService = itemService; } // 箭头函数自动绑定this到类实例 getAll = async (req: Request, res: Response) => { const items = await this.itemService.getAll(); res.status(200).json(items); } } export default ItemController;
额外说明
两种方案均解决了this指向问题,同时修正了依赖注入错误,确保使用传入的ItemService实例,提升代码的可测试性和扩展性。
内容的提问来源于stack exchange,提问作者Matheus Montemurro

