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

SvelteKit路由升级后+page.js报错:Cannot read properties of undefined (reading 'params')

错误原因与解决办法

错误原因

你遇到的Cannot read properties of undefined (reading 'params')错误,是因为SvelteKit新版路由(+page.js模式)中,load函数的参数结构已发生变化——不再通过page对象传递路由参数,直接解构params即可获取。你的代码仍沿用旧版路由的写法,导致page变量为undefined,访问page.params时触发报错。

解决办法

修改load函数的参数解构逻辑,直接提取params,而非从page对象中获取:

export async function load({ params }) {
   const songId = params.songId;
   const itunesSearched = await fetch(
    `https://itunes.apple.com/search?term=${songId}&entity=song`
  );
  const res = await itunesSearched.json();
  const songResults = res.results?.[0]; // 可选链避免无结果时报错
  return { songResults }
}

额外建议:添加可选链操作符?.访问res.results[0],避免当搜索无结果时出现新的Cannot read properties of undefined (reading '0')错误;同时尽量使用const替代var,提升代码稳定性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 22:40:41