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

React中Reflect.metadata无法生效,TypeScript装饰器元数据获取返回undefined

问题原因及解决方案

你遇到的问题是因为属性装饰器的元数据存储在类的原型对象上,而非类的实例上,但你调用getFormat时传入的是MyData的实例data,导致Reflect.getMetadata无法找到对应的元数据,返回undefined。

解决方法

方法1:修改getFormat的调用参数

直接传入类的原型对象,而不是实例:

const MyComponent = (props) => {
  const { data } = props;
  // 从实例的构造函数原型上获取元数据
  const meta = getFormat(data.constructor.prototype, "dateString");
  // ...
};

方法2:优化getFormat函数自动兼容实例和原型

修改getFormat,让它自动判断传入的是实例还是原型/类,统一从正确的目标获取元数据:

export function getFormat(target: any, propertyKey: string) {
  // 若传入的是实例,则切换到其构造函数的原型
  const targetObj = target.prototype ? target : target.constructor.prototype;
  return Reflect.getMetadata(formatMetadataKey, targetObj, propertyKey);
}

之后你可以直接用原来的调用方式getFormat(data, "dateString"),函数会自动处理。

必要配置检查

确保你的tsconfig.json已经开启装饰器和元数据相关的编译选项,否则装饰器元数据不会被正确生成:

{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    // 其他编译配置...
  }
}

同时确认已经安装了reflect-metadata包,且在代码最顶部完成导入(你已经在装饰器文件中导入,这一步没问题)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 06:20:23