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

React报错'arguments' is only allowed in functions and class methods排查

错误原因
  • 你在类中定义的updateConnection是类字段箭头函数,不属于标准的类原型方法。箭头函数本身不会绑定专属的arguments对象,而类字段的初始化位置在类体作用域,不存在外层函数提供的arguments可供继承,语法解析阶段就会直接抛出你看到的错误。
  • 额外隐藏问题:你类内定义的方法和外部导入的API方法完全同名,就算解决了arguments的语法错误,无参分支调用updateConnection时会优先匹配类实例自身的方法,触发无限递归导致栈溢出。
修复方法

优先推荐用剩余参数语法替代arguments,不需要修改原有箭头函数的写法,也不用额外处理this绑定问题,同时要解决方法重名的隐患:

// 给导入的API方法重命名,避免和类内方法重名
import { updateConnection as updateConnectionApi } from '../connections';

export default class Connection extends React.PureComponent {
    // 用剩余参数...args接收所有传入的实参
    updateConnection = (...args) => {
        if (args.length === 0) {
            updateConnectionApi(this.state.connection);
            return;
        }
        // 解构拿到原有参数,保留默认值逻辑
        const [name, value, save = true] = args;
        
        // 后续原有业务逻辑
    }
}

如果你更习惯用普通类方法的写法,也可以把箭头函数改成类原型方法,这时候可以正常使用arguments,但需要手动绑定this避免回调场景下this指向错误:

import { updateConnection as updateConnectionApi } from '../connections';

export default class Connection extends React.PureComponent {
    constructor(props) {
        super(props);
        // 手动绑定this
        this.updateConnection = this.updateConnection.bind(this);
    }

    updateConnection(name, value, save = true) {
        if (arguments.length === 0) {
            updateConnectionApi(this.state.connection);
            return;
        }

        // 后续原有业务逻辑
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 01:27:17