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

React history路由跳转带特殊符号URL报URIError问题求解

问题描述
  • 更新包含特殊符号的详情数据后,点击“编辑”按钮无任何响应;若详情数据不含特殊符号,点击编辑按钮可正常触发响应。
  • 问题复现截图:
    img1
  • 初始控制台报错:
history.js:93 Uncaught (in promise) URIError: Pathname "/branch-management/edit-branch/?companyName=ABC SDN BHD 1!@#$%^&*&branchName=ABC 1!@#$%^&*(" could not be decoded. This is likely caused by an invalid percent-encoding.
  • 初始问题业务代码:
const selectRow = async (code, companyName, e) => {
    e.preventDefault();
    history.push({
      pathname: `/branch-management/edit-branch/?companyName=${companyName}&branchName=${code}`,
    });
  };
  • 已尝试修复方案:使用encodeURIComponent对查询参数编码,但未生效,修改后抛出新错误Uncaught URIError: URI malformed,尝试代码如下:
const selectRow = async (code, companyName, e) => {
    const encodedCompanyName = encodeURIComponent(companyName);
    const encodedCode = encodeURIComponent(code);
    e.preventDefault();
    history.push({
      pathname: `/branch-management/edit-branch/?companyName=${encodedCompanyName}&branchName=${encodedCode}`,
    });
  };

涉及的encodeURIComponent类型定义:

declare function encodeURIComponent(uriComponent: string | number | boolean): string;
问题原因
  1. 核心用法错误:history.push的配置对象中,pathname字段仅接收纯路径内容,查询参数不属于路径段。你直接把带?、&的查询串拼在pathname末尾,history库会对整个pathname做严格的URI合规校验,带特殊语义的字符混在路径里会直接触发解码失败。
  2. 你之前用encodeURIComponent编码参数的逻辑本身是对的,但编码后的字符串依然被放在pathname字段中当做路径内容校验,才会抛出URI malformed的新错误。
正确修复方案

将查询参数从pathname中剥离,放到专门的search配置项中即可。推荐使用原生URLSearchParams处理查询串,它会自动完成参数值编码,避免手动拼接漏编码、错拼分隔符的问题:

const selectRow = async (code, companyName, e) => {
    e.preventDefault();
    const searchParams = new URLSearchParams();
    searchParams.set('companyName', companyName);
    searchParams.set('branchName', code);
    history.push({
      pathname: '/branch-management/edit-branch/',
      search: searchParams.toString()
    });
  };

如果你的运行环境不支持URLSearchParams,手动拼接的正确写法如下,注意不要把查询串拼到pathname里:

const selectRow = async (code, companyName, e) => {
    e.preventDefault();
    const encodedCompanyName = encodeURIComponent(companyName);
    const encodedCode = encodeURIComponent(code);
    history.push({
      pathname: '/branch-management/edit-branch/',
      search: `companyName=${encodedCompanyName}&branchName=${encodedCode}`
    });
  };

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 17:09:24