How to change editor theme dinamically

I tried with this:

var theme = new Compartment;

function setTheme(view, tema) {
view.dispatch({
effects: theme.reconfigure(view.theme.of(tema))
})
}

but i get the error: “Cannot read properties of undefined (reading ‘of’)”