Arrow function in class nextjs generate "use server" error

212 views Asked by At

I'm implementing mobx in a nextjs app and when I created a class and tried to use it in a component I got the following error:

Error: Functions cannot be passed directly to Client Components unless you explicitly expose it by marking it with "use server".

The class:

class Card {
  _card: TCard = {
    wordsToRelate: "",
    relationToRelate: "",
  };

  constructor() {
    makeAutoObservable(this);
  }

  doSomething = () => {    
    //doing something
  }
}

Changing the arrow function to a regular function fix the issue:

class Card {
  _card: TCard = {
    wordsToRelate: "",
    relationToRelate: "",
  };

  constructor() {
    makeAutoObservable(this);
  }

  doSomething() {
    //doing something
  }
}

Making questions to myself like:
Why this happen? Why cant I use arrow function inside a class ?

You should avoid using arrow functions in class as they won't be the part of prototype and thus not shared by every instance. It is same as giving the same copy of function to every instance.

I could't find an answer to:

Why an arrow function inside a class generate the 'use server' error?

0

There are 0 answers