You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Deno中使用UseCase类触发TypeError:无法读取undefined的getAppInfosUseCase属性

解决Deno + Oak中UseCase控制器的this上下文丢失问题

错误原因

在Oak路由中直接传递控制器的handle方法作为回调时,方法的this上下文会丢失,不再指向控制器实例,导致this.getAppInfosUseCase为undefined,触发TypeError: Cannot read properties of undefined (reading 'getAppInfosUseCase')错误。

解决方案

方案1:用箭头函数包裹回调

修改src/routes.ts中的路由定义,通过箭头函数保留控制器实例的上下文:

import { Router } from 'https://deno.land/x/oak@v10.6.0/router.ts';
import { getAppInfosController } from './useCases/GetAppInfos/index.ts';

const router = new Router();

// 用箭头函数包裹,确保this指向getAppInfosController实例
router.get('/', (ctx) => getAppInfosController.handle(ctx));

export { router };

方案2:将handle方法定义为箭头函数

修改src/useCases/GetAppInfos/GetAppInfosController.ts,把handle方法改成类属性箭头函数,自动绑定this到控制器实例:

import { Context } from 'https://deno.land/x/oak@v10.6.0/context.ts';
import { GetAppInfosUseCase } from './GetAppInfosUseCase.ts';

export class GetAppInfosController {
    constructor(
        private getAppInfosUseCase: GetAppInfosUseCase,
    ) {}

    // 箭头函数自动绑定this
    handle = (context: Context) => {
        context.response.status = 200;
        return context.response.body = this.getAppInfosUseCase.execute();
    }
}

验证修改效果

修改后重新启动服务,访问http://127.0.0.1:3030/,应该能正常返回:

{"author":"Jphn","github":"github.com/Jphn"}

内容的提问来源于stack exchange,提问作者João Pedro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 08:24:19