Ngxs开发求助:调用getState()时提示‘state is undefined’错误
Hey there! Let's troubleshoot that frustrating state is undefined error you're hitting when using NGXS. I've looked over your code, and here are the most common fixes to get things working:
1. You Forgot to Register Your State in NgModule
This is the #1 mistake beginners make with NGXS. If your TutorialState isn't added to NgxsModule.forRoot(), the store has no idea it exists—so calling getState() will return undefined.
Fix it by updating your AppModule (or the relevant feature module) to include your state:
import { NgModule } from '@angular/core'; import { NgxsModule } from '@ngxs/store'; import { TutorialState } from './path-to-your/tutorial.state'; @NgModule({ imports: [ // Register all your root states here NgxsModule.forRoot([TutorialState]) ] }) export class AppModule { }
2. Try Using the Full StateContext Object Instead of Destructuring
While your destructuring of { getState, patchState } looks correct, some versions of NGXS can have edge cases with this syntax. Switching to using the full context object often resolves this:
Update your action handler in TutorialState:
@Action(AddTutorial) addTutorial(context: StateContext<TutorialStateModel>, { payload }: AddTutorial) { // Call getState directly on the context object const state = context.getState(); context.patchState({ tutorial: [...state.tutorial, payload] }); }
3. Verify Your State Model and Defaults
Double-check that your state model and default values are properly configured. Using an interface for your state model is more idiomatic in TypeScript than a class (since it's just a data structure):
// Replace the class with an interface export interface TutorialStateModel { tutorial: any[]; } @State<TutorialStateModel>({ name: 'tutorial', defaults: { tutorial: [] // This matches the interface correctly } }) export class TutorialState { // ... rest of your code }
4. Confirm Store Injection in Your Component
Make sure you're correctly injecting the NGXS Store into your component. A missing or incorrect injection could lead to unexpected behavior when dispatching actions:
import { Component, OnInit } from '@angular/core'; import { Store } from '@ngxs/store'; import { AddTutorial } from './path-to-your/tutorial.actions'; @Component({ selector: 'app-your-component', templateUrl: './your-component.component.html' }) export class YourComponent implements OnInit { // Inject the Store via constructor constructor(private store: Store) {} ngOnInit() { this.store.dispatch(new AddTutorial('Redux')); } }
Most Likely Root Cause
9 times out of 10, the issue is that your TutorialState isn't registered in NgxsModule.forRoot(). Start with that fix, and your error should disappear!
内容的提问来源于stack exchange,提问作者Jonathan Lightbringer

