Next.js+TypeScript中使用Mobx@observable装饰器报错求助
Mobx装饰器语法报错解决方案
问题详情
错误信息
./src/app/stores/resource_store.ts Error: × Unexpected token `@`. Expected identifier, string literal, numeric literal or [ for the computed key ╭─[/Users/paulweijtens/PycharmProjects/take-step/with-redux/src/app/stores/resource_store.ts:3:1] 3 │ import {createContext} from "react"; 4 │ 5 │ export class ResourceStore { 6 │ @observable accessor resources: Map<string, Decimal> = new Map();
相关代码
export class ResourceStore { @observable accessor resources: Map<string, Decimal> = new Map(); }
当前tsconfig配置
{ "compilerOptions": { "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, "skipLibCheck": true, "strict": true, "noEmit": true, "esModuleInterop": true, "module": "esnext", "moduleResolution": "bundler", "resolveJsonModule": true, "isolatedModules": true, "jsx": "preserve", "incremental": true, "target": "es2015", "plugins": [ { "name": "next" } ], "paths": { "@/*": ["./src/*"] } }, "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], "exclude": ["node_modules"] }
用户疑问:TypeScript(或Next.js)是否不支持现代JavaScript装饰器?或者应该设置何种target?即使将target设为es2022并使用Node.js 21,仍存在相同问题。
原因与解决方法
核心原因
报错并非target版本或Node.js版本问题,而是TypeScript默认未启用装饰器语法支持,且Mobx当前使用的是旧版实验性装饰器标准,与TC39新装饰器标准不兼容。
解决方法
方法1:启用实验性装饰器配置
修改tsconfig.json的compilerOptions,添加以下配置:
{ "compilerOptions": { // ... 保留原有配置 "target": "es2022", // 适配accessor语法(TypeScript 4.9+支持) "experimentalDecorators": true, // 启用旧版实验性装饰器 "useDefineForClassFields": false // 禁用类字段新标准,避免与Mobx装饰器冲突 } }
方法2:改用Mobx无装饰器写法(推荐)
Mobx 6+推荐使用makeAutoObservable或makeObservable替代装饰器,无需依赖实验性语法配置:
import { makeAutoObservable } from "mobx"; export class ResourceStore { resources: Map<string, Decimal> = new Map(); constructor() { makeAutoObservable(this); } }
这种写法更符合标准JS/TS规范,也避免了装饰器的兼容性问题。
内容的提问来源于stack exchange,提问作者paul23
相关产品推荐
相关产品推荐

