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

SvelteKit嵌套属性读取报错:Cannot read properties of undefined

问题原因及解决办法

核心原因

你的代码里,data store的初始值是writable({}),页面第一次渲染时,fetch请求还没完成,$data是空对象。这时候:

  • 访问$data.item/$data.address:空对象读取不存在的属性只会返回undefined,不会触发报错,只是页面显示undefined;
  • 访问$data.city.school:先读取$data.city得到undefined,再试图读取undefined.school就会直接抛出Cannot read properties of undefined (reading 'school')的错误,最终表现为你遇到的undefined问题。

就算后续请求完成、数据更新,初始渲染时的错误可能已经导致组件渲染失败,后续数据更新也无法正常显示嵌套属性。

解决办法

有几种简单的处理方式:

  • 使用可选链操作符:给链式访问加?.,避免空值报错
<p>school: {$data.city?.school}</p>
  • 初始化store时给嵌套结构默认值:让初始的data包含city空对象,避免链式访问中断
const data = writable({ city: {} })
  • 条件渲染:确保city存在后再渲染对应内容
{#if $data.city}
  <p>school: {$data.city.school}</p>
{/if}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 07:22:16