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

React Native中Inversify构造函数注入报Cannot read property错误

问题解决:Inversify依赖注入后出现Cannot read properties of undefined (reading 'login')

核心问题分析

你遇到的错误本质是注入的loginUseCaseTwo实例为undefined,通常是因为依赖类未正确配置Inversify的注入规则,或者TypeScript装饰器相关配置缺失导致的。


解决方案

1. 给LoginUseCaseTwo添加@injectable()装饰器

Inversify要求所有需要被容器管理的类必须标记@injectable(),如果LoginUseCaseTwo未添加该装饰器,容器无法正确实例化它,注入到LoginUseCase时就会返回undefined。

修改LoginUseCaseTwo.ts:

import { injectable } from "inversify";
import { ILoginUseCaseTwo } from "./ILoginTwoUseCase";

@injectable() // 必须添加此装饰器
export class LoginUseCaseTwo implements ILoginUseCaseTwo {
    async login(username: string, password: string): Promise<boolean> {
        // 你的业务逻辑实现
        console.log("LoginUseCaseTwo执行登录逻辑");
        return Promise.resolve(true);
    }
}

2. 检查TypeScript配置是否开启装饰器相关选项

Inversify依赖TypeScript的装饰器和元数据功能,确保tsconfig.json中包含以下配置:

{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    // 其他已有配置...
  }
}

3. 调整容器绑定顺序(可选,规避潜在依赖顺序问题)

将被依赖的类(LoginUseCaseTwo)绑定放在前面,确保容器优先实例化依赖项:

// inversify.config.ts
const container = new Container();
// 先绑定依赖类
container.bind<ILoginUseCaseTwo>(TYPESTWO.ILoginUseCaseTwo).to(LoginUseCaseTwo);
// 再绑定被依赖类
container.bind<ILoginUseCase>(TYPES.ILoginUseCase).to(LoginUseCase);

4. 确保reflect-metadata在最顶部导入

reflect-metadata需要在所有Inversify相关代码执行前导入,建议在项目入口文件(如RootLayout.tsx)最顶部导入:

// RootLayout.tsx
import 'reflect-metadata'; // 必须放在所有导入的最开头
// 其他导入代码...

验证

完成上述修改后,重启项目并调用登录方法,loginUseCaseTwo会被正确注入,不会再出现undefined相关错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 09:48:09