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

Next.js 15构建遇ESLint未使用error变量报错,如何针对性忽略?

解决ESLint未使用catch变量报错的几种方法

针对你遇到的@typescript-eslint/no-unused-vars报错(catch块里的error变量定义但未使用),有以下几种针对性处理方式:

1. 单行局部忽略(推荐,仅针对当前代码)

方法A:添加ESLint忽略注释

直接在catch的变量行添加注释,精准跳过当前报错:

const getPokemon = async (id: string) => {
    try {
        const pokemon = await fetch(`https://pokeapi.co/api/v2/pokemon/${id}`, {
            cache: "force-cache"
        }).then(res => res.json());
        return pokemon;
    } catch (error) { // eslint-disable-line @typescript-eslint/no-unused-vars
        notFound();
    }
};

也可以把注释写在变量上方:

catch (
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    error
) {
    notFound();
}

方法B:用下划线前缀标记未使用变量

TypeScript和ESLint都默认认可下划线开头的变量为“故意不使用”,不会触发报错:

const getPokemon = async (id: string) => {
    try {
        const pokemon = await fetch(`https://pokeapi.co/api/v2/pokemon/${id}`, {
            cache: "force-cache"
        }).then(res => res.json());
        return pokemon;
    } catch (_error) {
        notFound();
    }
};

2. 全局配置(对整个项目生效)

你之前配置no-unused-vars没效果,是因为Next.js的TypeScript环境用的是TS专属规则@typescript-eslint/no-unused-vars,而非原生ESLint的no-unused-vars。修改你的.eslintrc.json:

{
    "extends": ["next/core-web-vitals", "next/typescript"],
    "rules": {
        "@typescript-eslint/no-unused-vars": [
            "error",
            {
                "caughtErrorsIgnorePattern": "^_" // 忽略catch中以下划线开头的变量
            }
        ]
    }
}

如果想直接允许所有未使用的catch错误变量,也可以这么配:

{
    "extends": ["next/core-web-vitals", "next/typescript"],
    "rules": {
        "@typescript-eslint/no-unused-vars": [
            "error",
            {
                "caughtErrors": "none" // 完全忽略catch里未使用的错误变量
            }
        ]
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 14:37:10