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

在NestJS中注入ObjectionJS模型触发调用栈溢出异常如何解决

问题根因

这个Maximum call stack size exceeded编译报错是Objection.js 3.x版本的类型定义和TypeScript非严格模式不兼容导致的。Objection 3的类型系统重度依赖TypeScript严格模式下的类型推导终止规则,关闭严格模式时,类型递归推导没有边界,就会触发栈溢出。你开启strict: true后编译正常也正好对应这个原因。


解决方法

方法1:单独开启必要的严格子规则(不需要全局开启严格模式)

如果你的项目历史代码不支持全局开启严格模式,可以只在tsconfig.json的compilerOptions中开启以下几个Objection依赖的规则即可:

{
  "compilerOptions": {
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "strictPropertyInitialization": true,
    "esModuleInterop": true
  }
}

这些规则是strict: true的子集,不会引入额外的严格校验逻辑,同时可以解决Objection的类型推导死循环问题。

方法2:给模型类显式声明类型,切断递归推导

如果开启上面的规则还是报错,可以给你的模型类增加显式的$type声明,手动终止类型递归:
BaseModel修改如下:

import { Model, ModelObject } from 'objection';

export default class BaseModel extends Model {
  declare $type: ModelObject<BaseModel>;

  readonly id: number;
  createdBy: number;
  created!: string;
  modified: string;
  modifiedBy: number; 
}

UserModel修改如下:

import { ModelObject } from 'objection';
import BaseModel from './base.model';

export default class UserModel extends BaseModel {
  declare $type: ModelObject<UserModel>;

  static tableName = 'users';
  static virtualAttributes = ['fullName'];

  firstName!: string;
  lastName!: string;
  company?: string;
  email!: string;

  fullName(): string {
    return `${this.firstName} ${this.lastName}`;
  }

  static jsonSchema = {
    type: 'object',
    required: ['firstName', 'lastName', 'email'],
    properties: {
      id: { type: 'number' },
      firstName: { type: 'string' },
      lastName: { type: 'string' },
      company: { type: 'string' },
      email: { type: 'string' },
    },
  };
}

方法3:全局开启严格模式

如果项目允许,直接在tsconfig.json中设置"strict": true是最稳妥的方案,这也是Objection.js 3官方文档推荐的TypeScript搭配用法,除了可以解决这个编译报错外,还能降低项目整体的类型问题风险。


额外校验

确认你的模块中Objection模型的注册逻辑正确,示例如下:

// 对应模块的providers配置
@Module({
  providers: [
    {
      provide: 'UserModel',
      useValue: UserModel,
    },
    UserService
  ]
})
export class UserModule {}

内容的提问来源于stack exchange,提问作者Fluffy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 17:36:04