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
相关产品推荐
相关产品推荐

