One theory to explain humor is that it is the mental state of "flipping" between two or more conceptualizations of the same thing. You find input humorous when it is unexpected and different from your current model of reality, and you are forced to add that new input to your list of expectations. The effect relies on your imagination in knowing what will probably happen, and your confusion when it doesn't happen. Whether or not something is funny depends not only on how unexpected that input is, but on your internal state and thoughts about the input.

Thus when a school bus randomly explodes on the Simpsons, it's funny, whereas when a firework does the same thing in Real Life, it is not. This also explains why a stimulus that is humorous the first time is less so, or not at all, the second. This is most noticeable in very predictable humor like the Three Stooges or TV sitcoms. If a humorous input is sufficiently complex or draws upon concepts that aren't often referenced in daily life, it can be funny more often, as is the case with Monty Python and SOY!. There is a point of diminishing returns with regard to complexity and obscurity, however, as most people just don't find jokes told in Calculus notation or about Millard Fillmore very funny. Dependence upon forethought and imagination also explains why dull people often lack a sense of humor.

Another facet of this theory is that your physiological, emotional, and cognitive states can "block" you from making the associations and preconceptions necessary to find humor in a situation. When you walk into a pole you don't see, you don't laugh because you are busy being in pain, but when you look back on the incident in a week, it's hilarious and you can laugh along with your friends at the memory. Likewise, when you're crying about something, you are probably using the whole of your concentration and emotional depth on that thing, and cannot or are not willing to spend the thought needed to appreciate a funny stimulus. Humor can also be interfered with by a deeply held belief or opinion, which is why the strongly Christian find no humor in jokes about Jesus. Similarly, it's hard to laugh at yourself, because deep down we don't consider ourselves buffoons, and are not willing to examine the possibility that we might be.

It should be noted that under this theory, when we find something funny, we incorporate it to a small degree into our entire thought process. In essence, we learn it. That's why upon reading Hitchhikers Guide the second time, we take almost as much pleasure in anticipating the humorous parts as we do in reading them. That's also why racist/sexist humor is so insidious, because in laughing at it, we incorporate it into our psyche as a plausible (although not necessarily true) fact.

For more on this theory, see:
Belief and the Basis of Humor, Hugh LaFollette and Niall Shanks, American Philosophical Quarterly, 1993, 329-39
Laughter, Robert R. Provine, American Scientist, 1996 Jan-Feb