I tend to work on the principle that much humour relies on cognitive dissonance - on the foreground not matching the background, on the protagonist's response to a situation being inappropriate, and so on.