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

JavaScript嵌套对象解构设默认值仍报'Cannot read properties of null'错误

问题描述

我在JavaScript中尝试解构对象,已在解构时设置默认值,但仍出现以下错误:
React Router caught the following error during render TypeError: Cannot read properties of null (reading 'responseTimePoints')

我的解构代码如下:

const testRun = useTestRunModel();

const {
    id: testRunId,
    graphData: { responseTimePoints = [] } = {},
} = testRun || {};

testRun对象中graphData字段为null,我希望当testRun/testRun.graphData/testRun.graphData.responseTimePoints为null或undefined时,responseTimePoints被设为空数组。

技术栈:React 18.2 + TypeScript 5.1.6,tsconfig.json配置如下:

"compilerOptions": {
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "module": "esnext",
    "target": "es2015",
    "allowJs": false,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "isolatedModules": true,
    "jsx": "react-jsx",
    "moduleResolution": "node",
    "noEmit": true,
    "noFallthroughCasesInSwitch": true,
    "resolveJsonModule": true,
    "skipLibCheck": true,
    "strict": true,
    "baseUrl": "./",
    "rootDir": "./",
    "types": []
  }
解决方案

问题核心:你给graphData设置的默认值{}仅在graphData为undefined时生效,但当前graphData是null,解构null的属性会直接抛出错误。

以下两种方式可以解决问题:

方式一:使用可选链+空值合并运算符

最直观的写法,直接逐层处理null/undefined情况:

const testRun = useTestRunModel();

const testRunId = testRun?.id;
const responseTimePoints = testRun?.graphData?.responseTimePoints ?? [];

方式二:优化解构逻辑

先单独取出graphData,再用??运算符处理null情况后解构:

const testRun = useTestRunModel();

const {
    id: testRunId,
    graphData,
} = testRun || {};
const { responseTimePoints = [] } = graphData ?? {};

额外建议(TypeScript适配)

结合你的严格模式配置,建议给testRun和graphData定义明确类型,避免类型推断问题:

interface GraphData {
  responseTimePoints?: number[];
  // 补充graphData的其他字段类型
}

interface TestRun {
  id?: string;
  graphData?: GraphData | null;
  // 补充testRun的其他字段类型
}

// 确保useTestRunModel返回正确类型,或通过类型断言修正
const testRun = useTestRunModel() as TestRun;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 20:57:47