使用RTK Query时遇JSON.parse语法错误,求排查方向
问题:RTK Query解析字符串ID时出现JSON.parse错误
我在开发React组件,需要发起一系列RTK Query调用,其中一个调用要获取关联文档ID,作为另一个调用的参数。现在遇到错误:SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 3 of the JSON data
查询返回日志显示了目标数据,但找不到违规字符,Postman返回的也是相同的无引号字符串,没有尾随字符:
status:"rejected" endpointName:"getCurrentPlan" requestId:"GTR3VTWcO7pIyc2UBWGVs" originalArgs:"6205a8313fe12d6b4ec354c4" startedTimeStamp:1661294881186 status:"PARSING_ERROR" originalStatus:200 data:"62c9d3f6053cf23ca515fad1" error:"SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 3 of the JSON data"
查询调用代码:
getCurrentPlan: builder.query({ query: clientId => `/clientapi/clients/${clientId}/plan`, })
组件调用代码:
const {data: planId, isSuccess: planSuccess} = useGetCurrentPlanQuery(clientId)
补充更新
附上后端方法,客户端模型的currentPlan字段是字符串,测试值62c9d3f6053cf23ca515fad1和RTK Query返回的数据一致,但仍出现JSON错误:
exports.getCurrentPlan = async (req, res) => { try { const { id } = req.params; const client = await Client.findById(id); const plan = client.currentPlan; res.send(plan); } catch { res.status(404) res.send({ error: "Current Plan not found"}) } }
解决办法
问题根源:RTK Query默认会将响应当作JSON解析,但后端返回的纯字符串(如62c9d3f6053cf23ca515fad1)不是合法JSON——JSON要求字符串必须用双引号包裹,所以解析失败。
有两种修复方案:
方案一:修改后端返回合法JSON
方式1:将字符串包裹在对象中返回:
res.send({ planId: plan });之后在组件中通过
planId.planId获取值。方式2:直接返回带双引号的字符串,并设置正确的响应头:
res.setHeader('Content-Type', 'application/json'); res.send(JSON.stringify(plan));
方案二:修改RTK Query配置,跳过JSON解析
在查询配置中添加responseHandler,告诉RTK Query直接返回纯文本:
getCurrentPlan: builder.query({ query: clientId => `/clientapi/clients/${clientId}/plan`, responseHandler: (response) => response.text() })
内容的提问来源于stack exchange,提问作者Jowz
相关产品推荐
相关产品推荐

