Skip to content
← Back to rules

oxc/no-this-in-exported-function Suspicious

作用

禁止在导出的函数中使用 this

为什么这不好?

在大多数打包器中,导出函数里的 this 值不会被保留。 当一个函数被导出并在另一个模块中导入时,this 通常会变成 undefined,而不是模块命名空间对象。这可能会导致 意外的运行时错误或不正确的行为。

示例

以下是此规则的错误代码示例:

javascript
export function foo() {
  console.log(this);
}

export default function bar() {
  this.something();
}

function baz() {
  const self = this;
}
export { baz };

以下是此规则的正确代码示例:

javascript
function foo() {
  console.log(this);
}

export const bar = () => {
  console.log(this);
};

如何使用

To enable this rule using the config file or in the CLI, you can use:

json
{
  "rules": {
    "oxc/no-this-in-exported-function": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  rules: {
    "oxc/no-this-in-exported-function": "error",
  },
});
bash
oxlint --deny oxc/no-this-in-exported-function

版本

此规则于 v1.33.0 中添加。

参考资料