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

自定义TypeORM仓库报错:Cannot read properties of undefined (reading 'create')

问题修复方案

1. 检查自定义装饰器的实现

你手写的CustomRepository装饰器大概率没正确关联TypeORM的数据源,这是this变为undefined的核心原因。

如果是NestJS环境,正确的装饰器和配套提供者写法如下:

typeorm-ex.decorator.ts:

import { SetMetadata } from '@nestjs/common';

export const TYPEORM_CUSTOM_REPOSITORY = 'TYPEORM_CUSTOM_REPOSITORY';

export function CustomRepository(entity: Function): ClassDecorator {
  return SetMetadata(TYPEORM_CUSTOM_REPOSITORY, entity);
}

typeorm-ex.providers.ts(处理仓库实例化逻辑):

import { Provider } from '@nestjs/common';
import { DataSource } from 'typeorm';
import { TYPEORM_CUSTOM_REPOSITORY } from './typeorm-ex.decorator';

export function getCustomRepositoryProviders(): Provider[] {
  const providers: Provider[] = [];
  const repositories = Reflect.getMetadata(TYPEORM_CUSTOM_REPOSITORY, Reflect) || [];

  repositories.forEach((repo) => {
    providers.push({
      provide: repo.repository,
      useFactory: (dataSource: DataSource) => dataSource.getRepository(repo.entity).extend(repo.repository),
      inject: [DataSource],
    });
  });

  return providers;
}

最后在User模块中注册这些提供者:

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { getCustomRepositoryProviders } from './typeorm-ex.providers';
import { User } from './user.entity';
import { UserRepository } from './user.repository';

@Module({
  imports: [TypeOrmModule.forFeature([User])],
  providers: [...getCustomRepositoryProviders()],
  exports: [UserRepository],
})
export class UserModule {}

2. 确保仓库通过依赖注入使用

在Service中必须通过构造函数注入仓库实例,绝对不能手动new:

import { Injectable } from '@nestjs/common';
import { UserRepository } from './user.repository';

@Injectable()
export class UserService {
  constructor(private readonly userRepo: UserRepository) {}

  async createUser(userData) {
    return this.userRepo.createUser(userData);
  }
}

3. 简化方案:跳过自定义装饰器

不想写额外装饰器的话,直接在模块里用DataSource扩展仓库:

// user.repository.ts 去掉@CustomRepository装饰器
import { Repository } from 'typeorm';
import { User } from './user.entity';

export class UserRepository extends Repository<User> {
  async createUser(userData: Partial<User>): Promise<User> {
    const user = this.create(userData);
    return this.save(user);
  }
}

// user.module.ts 直接注册仓库提供者
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { DataSource } from 'typeorm';
import { User } from './user.entity';
import { UserRepository } from './user.repository';

@Module({
  imports: [TypeOrmModule.forFeature([User])],
  providers: [
    {
      provide: UserRepository,
      useFactory: (dataSource: DataSource) => dataSource.getRepository(User).extend(UserRepository),
      inject: [DataSource],
    },
  ],
  exports: [UserRepository],
})
export class UserModule {}

为什么你之前的方法无效?

你遇到的this undefined问题,本质是仓库实例没被正确创建——要么装饰器没关联数据源,要么你没通过依赖注入获取实例,导致调用方法时this指向错误。加可选链或判断this.create只是掩盖问题,没有解决根源。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 00:22:20