React+Next.js报错:赋值表达式左侧必须是变量或属性访问
报错原因与修复方案
报错原因
你碰到的The left-hand side of an assignment expression must be a variable or a property access错误,核心原因是赋值语句左侧使用了可选链操作符(?.):
- 可选链
?.的设计是用来安全访问嵌套属性,一旦中间层级为undefined或null就会短路返回undefined,但赋值操作的左操作数必须是一个明确可被赋值的引用(变量或确定存在的属性),不能是可能为undefined的表达式。你代码里的statusUpdateRefreshReasonRef?.current?.value = ...直接违反了这个规则。 - 你用
@ts-ignore屏蔽了TypeScript的类型检查,但本质的语法逻辑问题并没有解决。
修复方案
方案1:明确引用后赋值(推荐)
既然useRef初始化时已经传入了{ value: [] },current永远不会是null或undefined,完全不需要用可选链。同时用扩展运算符正确克隆数组,避免引用混淆:
const statusUpdateRefreshReasonRef = useRef({ value: [], }); // 克隆ref中的数组,避免直接修改原引用 const cloneStatusUpdateClone = [...statusUpdateRefreshReasonRef.current.value]; if (cloneStatusUpdateClone.length) { cloneStatusUpdateClone.shift(); // 直接访问确定存在的属性,无需可选链 statusUpdateRefreshReasonRef.current.value = cloneStatusUpdateClone; setStatusUpdateRefreshReason([...cloneStatusUpdateClone]); }
方案2:直接修改原数组(简化写法)
如果你的业务场景不需要保留原数组的引用,可以直接修改ref中的数组,省去克隆后赋值的步骤:
const statusUpdateRefreshReasonRef = useRef({ value: [], }); const currentValue = statusUpdateRefreshReasonRef.current.value; if (currentValue.length) { currentValue.shift(); // 基于修改后的数组更新状态 setStatusUpdateRefreshReason([...currentValue]); }
注意:这种写法直接修改了ref中的原数组,若其他逻辑依赖该数组的原始状态,可能会引发意外副作用,需根据实际场景选择。
内容的提问来源于stack exchange,提问作者Akshat Sitapara
相关产品推荐
相关产品推荐

