15

解决pnpm (ERR_INVALID_THIS)异常 Node.js 20

 1 year ago
source link: https://www.wyr.me/post/746
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

在Node.js 20版本中,你可能会遇到如下异常:

 WARN  GET https://registry.npmjs.org/chatgpt/-/chatgpt-5.0.10.tgz error (ERR_INVALID_THIS). Will retry in 10 seconds. 2 retries left.

为了解决这个问题,你只需要升级到pnpm v8.3.1或更高版本。可以通过以下命令安装并激活指定版本的pnpm:

corepack prepare [email protected] --activate

问题原因及修复

这个问题的根本原因在于pnpm模块依赖的node-fetch库中,URLSearchParams.prototype[p].call()函数调用时,错误地把this上下文设置为了receiver(代理对象)而非target(原始对象)。将this上下文设置为receiver导致URLSearchParams的方法无法正确访问原始对象的属性和方法,进而抛出ERR_INVALID_THIS异常。

修复此问题的代码位于https://github.com/pnpm/node-fetch/blob/ebe57b3986135258dbac010b754fc54de4beb2a8/src/headers.js,具体更改如下:

return URLSearchParams.prototype[p].call(
    target,
    String(name).toLowerCase(),
    String(value)
);

通过将this上下文正确地设置为target(原始对象),URLSearchParams的方法可以正确访问原始对象的属性和方法,从而解决了ERR_INVALID_THIS异常。

如果你在使用Node.js 20时遇到了pnpm的ERR_INVALID_THIS异常,请升级到pnpm v8.3.1或更高版本。这个问题已经在新版pnpm中得到修复,升级后就能解决该问题。

注意: Node.js 20.0.0版本存在异常断流问题,请升级到Node.js 20.1.0版本。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK