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

无法找到匹配history.push()的正确AST选择器

解决ESLint禁止history.push调用的选择器问题

你之前的选择器无效,是因为对history.push()的AST结构判断有误:history.push对应的AST节点是MemberExpression,其中object字段指向name为"history"的Identifier节点,property字段指向name为"push"的Identifier节点,二者并非相邻兄弟节点,所以用相邻兄弟选择器+无法匹配。

正确的配置方式是直接匹配对应的MemberExpression节点,在ESLint配置文件中修改no-restricted-syntax规则:

{
  "rules": {
    "no-restricted-syntax": [
      "error",
      {
        "selector": "MemberExpression[object.name='history'][property.name='push']",
        "message": "请勿使用history.push,请改用React Router v6的useNavigate钩子"
      }
    ]
  }
}

如果需要同时禁止history.replace、history.goBack等其他历史记录操作,可以用正则匹配方法名:

{
  "rules": {
    "no-restricted-syntax": [
      "error",
      {
        "selector": "MemberExpression[object.name='history'][property.name=/^(push|replace|goBack)$/]",
        "message": "请勿使用history相关方法,请改用React Router v6的useNavigate钩子"
      }
    ]
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 02:18:19