Spotify API报错:TypeError: Converting circular structure to JSON 求助
解决
Uncaught (in promise) TypeError: Converting circular structure to JSON错误(Spotify播放列表保存功能) 问题根源分析
你的代码存在两个关键问题,其中一个直接触发了循环引用错误:
- 多余的
json: true配置项:原生浏览器fetchAPI不支持该参数,添加后会导致内部处理异常(部分场景下会尝试序列化包含循环引用的请求配置对象)。 - 潜在的参数类型异常:需确认传入的
playlistName确实是字符串类型,而非带循环引用的对象。
修复步骤
1. 移除无效的json: true配置
原生fetch不需要json: true参数——你已经通过Content-Type请求头和JSON.stringify()正确处理了请求体。删除所有fetch请求中的json: true行:
修复后的创建播放列表请求代码:
let playlistID = await fetch( `https://api.spotify.com/v1/users/${userID}/playlists`, { method: "POST", headers: { Authorization: `Bearer ${currentAccessToken}`, "Content-Type": "application/json", }, body: JSON.stringify({ name: playlistName }), } ) .then((response) => response.json()) .then((jsonResponse) => jsonResponse.id) .catch((error) => { console.log(`Playlist creation error: ${error}`); });
2. 验证参数类型
在savePlaylist函数开头添加日志,确认playlistName的类型和值:
async savePlaylist(playlistName, trackURIs) { console.log("playlistName类型:", typeof playlistName); console.log("playlistName值:", playlistName); if (!(playlistName && trackURIs)) return; // 后续逻辑... }
如果打印结果显示playlistName是对象类型,检查React组件中设置playlistName状态的代码,确保赋值的是字符串而非其他对象(比如误将track对象赋值给了该状态)。
3. 完善错误处理逻辑
当前userID获取失败时会返回undefined,导致后续请求报错。可以添加更严格的错误处理,终止异常流程:
let userID = await fetch("https://api.spotify.com/v1/me", { headers }) .then((response) => { if (!response.ok) throw new Error(`HTTP错误!状态码: ${response.status}`); return response.json(); }) .then((jsonResponse) => jsonResponse.id) .catch((error) => { console.error(`获取用户ID失败: ${error}`); throw error; // 抛出错误,避免后续无效请求 });
4. 优化函数调用
调用Spotify.savePlaylist时添加await(需确保调用函数为async),避免未处理的Promise:
async savePlaylist() { console.log('Saving playlist') let trackURIs = this.state.playlistTracks.map((track) => track.URI) await Spotify.savePlaylist(this.state.playlistName, trackURIs) // this.setState({playlistName: "", playlistTracks: []}) }
内容的提问来源于stack exchange,提问作者YSquid
相关产品推荐
相关产品推荐

