对象解构的异常行为:状态更新方法中的日志输出疑问
It looks like your payload is a class instance rather than a plain JavaScript object, which is why you're seeing inconsistent behavior when accessing properties directly vs. using classToPlain. Here are the most common fixes and explanations for this problem:
1. Direct Property Access Fails Due to Class Encapsulation
Many class-based models (especially when using libraries like class-transformer or TypeScript with private/protected properties) use getters, setters, or non-enumerable properties that don’t behave as expected when accessed directly on the instance. classToPlain works around this by converting the class instance into a plain object with all exposed properties.
Fix: Convert the payload to a plain object first before accessing properties or updating state:
@Action(RsRosCoughUiUpdate) rsRosCoughUiUpdate({ getState, patchState }: StateContext<IRs>, payload: IFormState) { // Convert class instance to a plain object const plainPayload = classToPlain(payload) as IFormState; // Now access properties reliably from the plain object console.log('PLAIN PAYLOAD STATUS', plainPayload.status); console.log('PLAIN PAYLOAD CHANGE', plainPayload.change); // Use the plain object for state updates to avoid unexpected behavior patchState({ ...getState(), ...plainPayload }); }
2. Destructuring the Original Class Instance Doesn’t Work
If you tried destructuring the original payload like const { status, change } = payload, this would fail because those properties aren’t enumerable or directly accessible on the class instance.
Fix: Destructure from the plain object instead:
const { status, change } = classToPlain(payload) as IFormState;
3. Ensure Your Class Exposes Properties Correctly
If you’re using class-transformer, make sure all properties you need to access are decorated with @Expose() (especially if you’re using @Exclude() on other properties) or that they’re public and enumerable. For example:
import { Expose } from 'class-transformer'; class FormState implements IFormState { @Expose() public status: string; @Expose() public change: any; // ... other class properties and methods }
Debugging Tip
To confirm this is the root issue, add these logs to your method:
console.log('Payload is class instance:', payload instanceof FormState); // Replace FormState with your actual class name console.log('Enumerable properties on payload:', Object.keys(payload));
If status or change don’t appear in Object.keys(payload), that confirms they’re non-enumerable or not directly accessible on the instance.
内容的提问来源于stack exchange,提问作者st_clair_clarke

