Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: ReferenceError: Cannot access 'Store' before initialization

I have a class Store which incapsulates State (mobx used).

export class Store<State> {
    @observable
    public state: State;

    constructor(protected rootStore: RootStore, state: State) {
        this.state = state || ({} as State);
    }

    @action
    setState(state: State) {
        this.state = {
            ...this.state,
            ...state
        };
    }
}

And I'm trying to implement a class UserState:

interface UserState {
    authorised?: boolean;
    loading?: boolean;
    name?: string;
    balance?: number;
}

export class UserStore extends Store<UserState> {
    constructor(rootStore: RootStore) {
        super(rootStore, {
            authorised: false,
            loading: true,
            name: ''
        })
    }
}

Everything seems right for me, but I have an error:

ReferenceError: Cannot access 'Store' before initialization

I simply trying to set some default values in a store and it seems in a Store it's inside a constructor, so it's initialized obviously.

enter image description here

like image 809
zishe Avatar asked Jun 02 '19 09:06

zishe


People also ask

How to fix Cannot access before initialization?

The "Cannot access before initialization" error occurs when a variable declared using let or const is accessed before it was initialized in the scope. To solve the error, make sure to initialize the variable before accessing it.

Can't access lexical declaration react?

The JavaScript exception "can't access lexical declaration `variable' before initialization" occurs when a lexical variable was accessed before it was initialized. This happens within any block statement, when let or const variables are accessed before the line in which they are declared is executed.


1 Answers

Problem was solved by moving Store class to isolated file, before it was in the same file as the global store.

like image 157
zishe Avatar answered Oct 17 '22 04:10

zishe