Use catch instead of finally for browser compatibility (#161)

This commit is contained in:
jarmit 2022-02-28 12:33:00 -08:00 коммит произвёл GitHub
Родитель 0c63b419ac
Коммит be5cb2f0b6
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
2 изменённых файлов: 29 добавлений и 4 удалений

Просмотреть файл

@ -1,5 +1,4 @@
import { action } from 'mobx';
import ActionCreator from './interfaces/ActionCreator';
import ActionMessage from './interfaces/ActionMessage';
import MutatorFunction from './interfaces/MutatorFunction';
@ -19,11 +18,14 @@ export default function mutator<TAction extends ActionMessage, TReturn>(
// Wrap the callback in a MobX action so it can modify the store
const actionType = getPrivateActionType(actionCreator);
let wrappedTarget = action(actionType, (actionMessage: TAction) => {
const globalContext = getGlobalContext();
try {
getGlobalContext().currentMutator = actionType;
globalContext.currentMutator = actionType;
target(actionMessage);
} finally {
getGlobalContext().currentMutator = null;
globalContext.currentMutator = null;
} catch (e) {
globalContext.currentMutator = null;
throw e;
}
});

Просмотреть файл

@ -80,4 +80,27 @@ describe('mutator', () => {
// Assert
expect(mockGlobalContext.currentMutator).toBe(null);
});
it('sets the currentMutator back to null if error is thrown', () => {
// Arrange
let actionCreator: any = {
__SATCHELJS_ACTION_ID: 'testAction',
__SATCHELJS_ACTION_TYPE: 'testActionType',
};
let callback: any = () => {
throw new Error('Error in Mutator');
};
mutator(actionCreator, callback);
// Act
let subscribedCallback = (dispatcher.subscribe as jasmine.Spy).calls.argsFor(0)[1];
try {
subscribedCallback();
} catch {
// no op
}
// Assert
expect(mockGlobalContext.currentMutator).toBe(null);
});
});